Completed
Branch FET/reg-form-builder/main (0f11d8)
by
unknown
02:56 queued 17s
created
caffeinated/modules/event_single_caff/EED_Event_Single_Caff.module.php 2 patches
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -26,228 +26,228 @@
 block discarded – undo
26 26
 {
27 27
 
28 28
 
29
-    /**
30
-     * @return EED_Event_Single_Caff
31
-     */
32
-    public static function instance()
33
-    {
34
-        return parent::get_instance(__CLASS__);
35
-    }
36
-
37
-
38
-    /**
39
-     *    set_hooks - for hooking into EE Core, other modules, etc
40
-     *
41
-     * @access    public
42
-     * @return    void
43
-     */
44
-    public static function set_hooks()
45
-    {
46
-    }
47
-
48
-    /**
49
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
50
-     *
51
-     * @access    public
52
-     * @return    void
53
-     */
54
-    public static function set_hooks_admin()
55
-    {
56
-        self::setDefinitions();
57
-        add_action(
58
-            'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_events__template_settings',
59
-            array('EED_Event_Single_Caff', 'load_scripts_styles'),
60
-            10
61
-        );
62
-        add_action(
63
-            'AHEE__template_settings__template__before_settings_form',
64
-            array('EED_Event_Single_Caff', 'template_settings_form'),
65
-            10
66
-        );
67
-        add_filter(
68
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
69
-            array('EED_Event_Single_Caff', 'update_template_settings'),
70
-            10,
71
-            2
72
-        );
73
-        // AJAX
74
-        add_action(
75
-            'wp_ajax_espresso_update_event_single_order',
76
-            array('EED_Event_Single_Caff', 'update_event_single_order')
77
-        );
78
-        add_action(
79
-            'wp_ajax_nopriv_espresso_update_event_single_order',
80
-            array('EED_Event_Single_Caff', 'update_event_single_order')
81
-        );
82
-    }
83
-
84
-
85
-    public static function load_scripts_styles()
86
-    {
87
-        add_action('admin_enqueue_scripts', array('EED_Event_Single_Caff', 'enqueue_scripts_styles'), 10);
88
-    }
89
-
90
-
91
-    public static function enqueue_scripts_styles()
92
-    {
93
-        wp_register_style(
94
-            'eed-event-single-sortable',
95
-            EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.css',
96
-            array(),
97
-            EVENT_ESPRESSO_VERSION
98
-        );
99
-        wp_enqueue_style('eed-event-single-sortable');
100
-        wp_register_script(
101
-            'eed-event-single-sortable',
102
-            EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.js',
103
-            array('espresso_core', 'jquery-ui-sortable'),
104
-            EVENT_ESPRESSO_VERSION,
105
-            true
106
-        );
107
-        wp_enqueue_script('eed-event-single-sortable');
108
-    }
109
-
110
-
111
-    /**
112
-     * Set constants only if they haven't been set yet.
113
-     */
114
-    public static function setDefinitions()
115
-    {
116
-        if (! defined('EVENT_SINGLE_CAFF_TEMPLATES_PATH')) {
117
-            define('EVENT_SINGLE_CAFF_TEMPLATES_PATH', plugin_dir_path(__FILE__) . 'templates/');
118
-            define('EVENT_SINGLE_CAFF_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
119
-        }
120
-    }
121
-
122
-
123
-    /**
124
-     *    template_settings_form
125
-     *
126
-     * @access    public
127
-     * @static
128
-     * @return    void
129
-     */
130
-    public static function template_settings_form()
131
-    {
132
-        $config = EE_Registry::instance()->CFG->template_settings;
133
-        $config = isset($config->EED_Event_Single) && $config->EED_Event_Single instanceof EE_Event_Single_Config
134
-            ? $config->EED_Event_Single : new EE_Event_Single_Config();
135
-        $config->use_sortable_display_order = isset($config->use_sortable_display_order)
136
-            ? $config->use_sortable_display_order : false;
137
-        $config = apply_filters('FHEE__EED_Event_Single__template_settings_form__event_list_config', $config);
138
-
139
-        $event_single_order_array = array();
140
-        $event_single_order_array[ $config->display_order_tickets ] = 'tickets';
141
-        $event_single_order_array[ $config->display_order_datetimes ] = 'datetimes';
142
-        $event_single_order_array[ $config->display_order_event ] = 'event';
143
-        $event_single_order_array[ $config->display_order_venue ] = 'venue';
144
-        // get template parts
145
-        $template_parts = EED_Event_Single::instance()->initialize_template_parts($config);
146
-        // convert to array so that we can add more properties
147
-        $config = get_object_vars($config);
148
-        $config['event_single_display_order'] = $template_parts->generate_sortable_list_of_template_parts(
149
-            'event-single-sortable-js',
150
-            '',
151
-            'single-sortable-li single-sortable-js'
152
-        );
153
-        EEH_Template::display_template(
154
-            EVENT_SINGLE_CAFF_TEMPLATES_PATH . 'admin-event-single-settings.template.php',
155
-            $config
156
-        );
157
-    }
158
-
159
-
160
-    /**
161
-     * update_template_settings
162
-     *
163
-     * @param EE_Template_Config $CFG
164
-     * @param array              $REQ
165
-     * @return EE_Template_Config
166
-     */
167
-    public static function update_template_settings(EE_Template_Config $CFG, $REQ)
168
-    {
169
-        if (! $CFG->EED_Event_Single instanceof EE_Event_Single_Config) {
170
-            $CFG->EED_Event_Single = new EE_Event_Single_Config();
171
-        }
172
-        $display_order_event = $CFG->EED_Event_Single->display_order_event !== null
173
-            ? $CFG->EED_Event_Single->display_order_event
174
-            : EED_Event_Single::EVENT_DETAILS_PRIORITY;
175
-        $display_order_datetimes = $CFG->EED_Event_Single->display_order_datetimes !== null
176
-            ? $CFG->EED_Event_Single->display_order_datetimes
177
-            : EED_Event_Single::EVENT_DATETIMES_PRIORITY;
178
-        $display_order_tickets = $CFG->EED_Event_Single->display_order_tickets !== null
179
-            ? $CFG->EED_Event_Single->display_order_tickets
180
-            : EED_Event_Single::EVENT_TICKETS_PRIORITY;
181
-        $display_order_venue = $CFG->EED_Event_Single->display_order_venue !== null
182
-            ? $CFG->EED_Event_Single->display_order_venue
183
-            : EED_Event_Single::EVENT_VENUES_PRIORITY;
184
-        $CFG->EED_Event_Single = new EE_Event_Single_Config();
185
-        $CFG->EED_Event_Single->display_status_banner_single = ! empty($REQ['display_status_banner_single'])
186
-                                                               && $REQ['display_status_banner_single'];
187
-        $CFG->EED_Event_Single->display_venue = ! empty($REQ['display_venue']) && $REQ['display_venue'];
188
-        $CFG->EED_Event_Single->use_sortable_display_order = ! empty($REQ['EED_Events_Single_use_sortable_display_order'])
189
-            ? absint($REQ['EED_Events_Single_use_sortable_display_order'])
190
-            : 0;
191
-        $CFG->EED_Event_Single->display_order_event = $CFG->EED_Event_Single->use_sortable_display_order
192
-            ? $display_order_event
193
-            : EED_Event_Single::EVENT_DETAILS_PRIORITY;
194
-        $CFG->EED_Event_Single->display_order_datetimes = $CFG->EED_Event_Single->use_sortable_display_order
195
-            ? $display_order_datetimes
196
-            : EED_Event_Single::EVENT_DATETIMES_PRIORITY;
197
-        $CFG->EED_Event_Single->display_order_tickets = $CFG->EED_Event_Single->use_sortable_display_order
198
-            ? $display_order_tickets
199
-            : EED_Event_Single::EVENT_TICKETS_PRIORITY;
200
-        $CFG->EED_Event_Single->display_order_venue = $CFG->EED_Event_Single->use_sortable_display_order
201
-            ? $display_order_venue
202
-            : EED_Event_Single::EVENT_VENUES_PRIORITY;
203
-        do_action('AHEE__EED_Event_Single__update_template_settings__after_update', $CFG, $REQ);
204
-        return $CFG;
205
-    }
206
-
207
-
208
-    /**
209
-     * update_event_single_order
210
-     *
211
-     * @access    public
212
-     * @return    void
213
-     */
214
-    public static function update_event_single_order()
215
-    {
216
-        $config_saved = false;
217
-        $template_parts = sanitize_text_field($_POST['elements']);
218
-        if (! empty($template_parts)) {
219
-            $template_parts = explode(',', trim($template_parts, ','));
220
-            foreach ($template_parts as $key => $template_part) {
221
-                $template_part = "display_order_$template_part";
222
-                $priority = ($key * 10) + EED_Event_Single::EVENT_DETAILS_PRIORITY;
223
-                EE_Registry::instance()->CFG->template_settings->EED_Event_Single->{$template_part} = $priority;
224
-                do_action("AHEE__EED_Event_Single__update_event_single_order__$template_part", $priority);
225
-            }
226
-            $config_saved = EE_Registry::instance()->CFG->update_espresso_config(false, false);
227
-        }
228
-        if ($config_saved) {
229
-            EE_Error::add_success(__('Display Order has been successfully updated.', 'event_espresso'));
230
-        } else {
231
-            EE_Error::add_error(
232
-                __('Display Order was not updated.', 'event_espresso'),
233
-                __FILE__,
234
-                __FUNCTION__,
235
-                __LINE__
236
-            );
237
-        }
238
-        echo wp_json_encode(EE_Error::get_notices(false));
239
-        exit();
240
-    }
241
-
242
-
243
-    /**
244
-     *    run - initial module setup
245
-     *
246
-     * @access    public
247
-     * @param WP $WP
248
-     * @return    void
249
-     */
250
-    public function run($WP)
251
-    {
252
-    }
29
+	/**
30
+	 * @return EED_Event_Single_Caff
31
+	 */
32
+	public static function instance()
33
+	{
34
+		return parent::get_instance(__CLASS__);
35
+	}
36
+
37
+
38
+	/**
39
+	 *    set_hooks - for hooking into EE Core, other modules, etc
40
+	 *
41
+	 * @access    public
42
+	 * @return    void
43
+	 */
44
+	public static function set_hooks()
45
+	{
46
+	}
47
+
48
+	/**
49
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
50
+	 *
51
+	 * @access    public
52
+	 * @return    void
53
+	 */
54
+	public static function set_hooks_admin()
55
+	{
56
+		self::setDefinitions();
57
+		add_action(
58
+			'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_events__template_settings',
59
+			array('EED_Event_Single_Caff', 'load_scripts_styles'),
60
+			10
61
+		);
62
+		add_action(
63
+			'AHEE__template_settings__template__before_settings_form',
64
+			array('EED_Event_Single_Caff', 'template_settings_form'),
65
+			10
66
+		);
67
+		add_filter(
68
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
69
+			array('EED_Event_Single_Caff', 'update_template_settings'),
70
+			10,
71
+			2
72
+		);
73
+		// AJAX
74
+		add_action(
75
+			'wp_ajax_espresso_update_event_single_order',
76
+			array('EED_Event_Single_Caff', 'update_event_single_order')
77
+		);
78
+		add_action(
79
+			'wp_ajax_nopriv_espresso_update_event_single_order',
80
+			array('EED_Event_Single_Caff', 'update_event_single_order')
81
+		);
82
+	}
83
+
84
+
85
+	public static function load_scripts_styles()
86
+	{
87
+		add_action('admin_enqueue_scripts', array('EED_Event_Single_Caff', 'enqueue_scripts_styles'), 10);
88
+	}
89
+
90
+
91
+	public static function enqueue_scripts_styles()
92
+	{
93
+		wp_register_style(
94
+			'eed-event-single-sortable',
95
+			EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.css',
96
+			array(),
97
+			EVENT_ESPRESSO_VERSION
98
+		);
99
+		wp_enqueue_style('eed-event-single-sortable');
100
+		wp_register_script(
101
+			'eed-event-single-sortable',
102
+			EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.js',
103
+			array('espresso_core', 'jquery-ui-sortable'),
104
+			EVENT_ESPRESSO_VERSION,
105
+			true
106
+		);
107
+		wp_enqueue_script('eed-event-single-sortable');
108
+	}
109
+
110
+
111
+	/**
112
+	 * Set constants only if they haven't been set yet.
113
+	 */
114
+	public static function setDefinitions()
115
+	{
116
+		if (! defined('EVENT_SINGLE_CAFF_TEMPLATES_PATH')) {
117
+			define('EVENT_SINGLE_CAFF_TEMPLATES_PATH', plugin_dir_path(__FILE__) . 'templates/');
118
+			define('EVENT_SINGLE_CAFF_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
119
+		}
120
+	}
121
+
122
+
123
+	/**
124
+	 *    template_settings_form
125
+	 *
126
+	 * @access    public
127
+	 * @static
128
+	 * @return    void
129
+	 */
130
+	public static function template_settings_form()
131
+	{
132
+		$config = EE_Registry::instance()->CFG->template_settings;
133
+		$config = isset($config->EED_Event_Single) && $config->EED_Event_Single instanceof EE_Event_Single_Config
134
+			? $config->EED_Event_Single : new EE_Event_Single_Config();
135
+		$config->use_sortable_display_order = isset($config->use_sortable_display_order)
136
+			? $config->use_sortable_display_order : false;
137
+		$config = apply_filters('FHEE__EED_Event_Single__template_settings_form__event_list_config', $config);
138
+
139
+		$event_single_order_array = array();
140
+		$event_single_order_array[ $config->display_order_tickets ] = 'tickets';
141
+		$event_single_order_array[ $config->display_order_datetimes ] = 'datetimes';
142
+		$event_single_order_array[ $config->display_order_event ] = 'event';
143
+		$event_single_order_array[ $config->display_order_venue ] = 'venue';
144
+		// get template parts
145
+		$template_parts = EED_Event_Single::instance()->initialize_template_parts($config);
146
+		// convert to array so that we can add more properties
147
+		$config = get_object_vars($config);
148
+		$config['event_single_display_order'] = $template_parts->generate_sortable_list_of_template_parts(
149
+			'event-single-sortable-js',
150
+			'',
151
+			'single-sortable-li single-sortable-js'
152
+		);
153
+		EEH_Template::display_template(
154
+			EVENT_SINGLE_CAFF_TEMPLATES_PATH . 'admin-event-single-settings.template.php',
155
+			$config
156
+		);
157
+	}
158
+
159
+
160
+	/**
161
+	 * update_template_settings
162
+	 *
163
+	 * @param EE_Template_Config $CFG
164
+	 * @param array              $REQ
165
+	 * @return EE_Template_Config
166
+	 */
167
+	public static function update_template_settings(EE_Template_Config $CFG, $REQ)
168
+	{
169
+		if (! $CFG->EED_Event_Single instanceof EE_Event_Single_Config) {
170
+			$CFG->EED_Event_Single = new EE_Event_Single_Config();
171
+		}
172
+		$display_order_event = $CFG->EED_Event_Single->display_order_event !== null
173
+			? $CFG->EED_Event_Single->display_order_event
174
+			: EED_Event_Single::EVENT_DETAILS_PRIORITY;
175
+		$display_order_datetimes = $CFG->EED_Event_Single->display_order_datetimes !== null
176
+			? $CFG->EED_Event_Single->display_order_datetimes
177
+			: EED_Event_Single::EVENT_DATETIMES_PRIORITY;
178
+		$display_order_tickets = $CFG->EED_Event_Single->display_order_tickets !== null
179
+			? $CFG->EED_Event_Single->display_order_tickets
180
+			: EED_Event_Single::EVENT_TICKETS_PRIORITY;
181
+		$display_order_venue = $CFG->EED_Event_Single->display_order_venue !== null
182
+			? $CFG->EED_Event_Single->display_order_venue
183
+			: EED_Event_Single::EVENT_VENUES_PRIORITY;
184
+		$CFG->EED_Event_Single = new EE_Event_Single_Config();
185
+		$CFG->EED_Event_Single->display_status_banner_single = ! empty($REQ['display_status_banner_single'])
186
+															   && $REQ['display_status_banner_single'];
187
+		$CFG->EED_Event_Single->display_venue = ! empty($REQ['display_venue']) && $REQ['display_venue'];
188
+		$CFG->EED_Event_Single->use_sortable_display_order = ! empty($REQ['EED_Events_Single_use_sortable_display_order'])
189
+			? absint($REQ['EED_Events_Single_use_sortable_display_order'])
190
+			: 0;
191
+		$CFG->EED_Event_Single->display_order_event = $CFG->EED_Event_Single->use_sortable_display_order
192
+			? $display_order_event
193
+			: EED_Event_Single::EVENT_DETAILS_PRIORITY;
194
+		$CFG->EED_Event_Single->display_order_datetimes = $CFG->EED_Event_Single->use_sortable_display_order
195
+			? $display_order_datetimes
196
+			: EED_Event_Single::EVENT_DATETIMES_PRIORITY;
197
+		$CFG->EED_Event_Single->display_order_tickets = $CFG->EED_Event_Single->use_sortable_display_order
198
+			? $display_order_tickets
199
+			: EED_Event_Single::EVENT_TICKETS_PRIORITY;
200
+		$CFG->EED_Event_Single->display_order_venue = $CFG->EED_Event_Single->use_sortable_display_order
201
+			? $display_order_venue
202
+			: EED_Event_Single::EVENT_VENUES_PRIORITY;
203
+		do_action('AHEE__EED_Event_Single__update_template_settings__after_update', $CFG, $REQ);
204
+		return $CFG;
205
+	}
206
+
207
+
208
+	/**
209
+	 * update_event_single_order
210
+	 *
211
+	 * @access    public
212
+	 * @return    void
213
+	 */
214
+	public static function update_event_single_order()
215
+	{
216
+		$config_saved = false;
217
+		$template_parts = sanitize_text_field($_POST['elements']);
218
+		if (! empty($template_parts)) {
219
+			$template_parts = explode(',', trim($template_parts, ','));
220
+			foreach ($template_parts as $key => $template_part) {
221
+				$template_part = "display_order_$template_part";
222
+				$priority = ($key * 10) + EED_Event_Single::EVENT_DETAILS_PRIORITY;
223
+				EE_Registry::instance()->CFG->template_settings->EED_Event_Single->{$template_part} = $priority;
224
+				do_action("AHEE__EED_Event_Single__update_event_single_order__$template_part", $priority);
225
+			}
226
+			$config_saved = EE_Registry::instance()->CFG->update_espresso_config(false, false);
227
+		}
228
+		if ($config_saved) {
229
+			EE_Error::add_success(__('Display Order has been successfully updated.', 'event_espresso'));
230
+		} else {
231
+			EE_Error::add_error(
232
+				__('Display Order was not updated.', 'event_espresso'),
233
+				__FILE__,
234
+				__FUNCTION__,
235
+				__LINE__
236
+			);
237
+		}
238
+		echo wp_json_encode(EE_Error::get_notices(false));
239
+		exit();
240
+	}
241
+
242
+
243
+	/**
244
+	 *    run - initial module setup
245
+	 *
246
+	 * @access    public
247
+	 * @param WP $WP
248
+	 * @return    void
249
+	 */
250
+	public function run($WP)
251
+	{
252
+	}
253 253
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -92,14 +92,14 @@  discard block
 block discarded – undo
92 92
     {
93 93
         wp_register_style(
94 94
             'eed-event-single-sortable',
95
-            EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.css',
95
+            EVENT_SINGLE_CAFF_ASSETS_URL.'eed_event_single_sortable.css',
96 96
             array(),
97 97
             EVENT_ESPRESSO_VERSION
98 98
         );
99 99
         wp_enqueue_style('eed-event-single-sortable');
100 100
         wp_register_script(
101 101
             'eed-event-single-sortable',
102
-            EVENT_SINGLE_CAFF_ASSETS_URL . 'eed_event_single_sortable.js',
102
+            EVENT_SINGLE_CAFF_ASSETS_URL.'eed_event_single_sortable.js',
103 103
             array('espresso_core', 'jquery-ui-sortable'),
104 104
             EVENT_ESPRESSO_VERSION,
105 105
             true
@@ -113,9 +113,9 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public static function setDefinitions()
115 115
     {
116
-        if (! defined('EVENT_SINGLE_CAFF_TEMPLATES_PATH')) {
117
-            define('EVENT_SINGLE_CAFF_TEMPLATES_PATH', plugin_dir_path(__FILE__) . 'templates/');
118
-            define('EVENT_SINGLE_CAFF_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets/');
116
+        if ( ! defined('EVENT_SINGLE_CAFF_TEMPLATES_PATH')) {
117
+            define('EVENT_SINGLE_CAFF_TEMPLATES_PATH', plugin_dir_path(__FILE__).'templates/');
118
+            define('EVENT_SINGLE_CAFF_ASSETS_URL', plugin_dir_url(__FILE__).'assets/');
119 119
         }
120 120
     }
121 121
 
@@ -137,10 +137,10 @@  discard block
 block discarded – undo
137 137
         $config = apply_filters('FHEE__EED_Event_Single__template_settings_form__event_list_config', $config);
138 138
 
139 139
         $event_single_order_array = array();
140
-        $event_single_order_array[ $config->display_order_tickets ] = 'tickets';
141
-        $event_single_order_array[ $config->display_order_datetimes ] = 'datetimes';
142
-        $event_single_order_array[ $config->display_order_event ] = 'event';
143
-        $event_single_order_array[ $config->display_order_venue ] = 'venue';
140
+        $event_single_order_array[$config->display_order_tickets] = 'tickets';
141
+        $event_single_order_array[$config->display_order_datetimes] = 'datetimes';
142
+        $event_single_order_array[$config->display_order_event] = 'event';
143
+        $event_single_order_array[$config->display_order_venue] = 'venue';
144 144
         // get template parts
145 145
         $template_parts = EED_Event_Single::instance()->initialize_template_parts($config);
146 146
         // convert to array so that we can add more properties
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
             'single-sortable-li single-sortable-js'
152 152
         );
153 153
         EEH_Template::display_template(
154
-            EVENT_SINGLE_CAFF_TEMPLATES_PATH . 'admin-event-single-settings.template.php',
154
+            EVENT_SINGLE_CAFF_TEMPLATES_PATH.'admin-event-single-settings.template.php',
155 155
             $config
156 156
         );
157 157
     }
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
      */
167 167
     public static function update_template_settings(EE_Template_Config $CFG, $REQ)
168 168
     {
169
-        if (! $CFG->EED_Event_Single instanceof EE_Event_Single_Config) {
169
+        if ( ! $CFG->EED_Event_Single instanceof EE_Event_Single_Config) {
170 170
             $CFG->EED_Event_Single = new EE_Event_Single_Config();
171 171
         }
172 172
         $display_order_event = $CFG->EED_Event_Single->display_order_event !== null
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
     {
216 216
         $config_saved = false;
217 217
         $template_parts = sanitize_text_field($_POST['elements']);
218
-        if (! empty($template_parts)) {
218
+        if ( ! empty($template_parts)) {
219 219
             $template_parts = explode(',', trim($template_parts, ','));
220 220
             foreach ($template_parts as $key => $template_part) {
221 221
                 $template_part = "display_order_$template_part";
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3347 added lines, -3347 removed lines patch added patch discarded remove patch
@@ -13,3363 +13,3363 @@
 block discarded – undo
13 13
 abstract class EE_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-        return $value;
708
-    }
709
-
710
-
711
-    /**
712
-     * set timezone, formats, and output for EE_Datetime_Field objects
713
-     *
714
-     * @param \EE_Datetime_Field $datetime_field
715
-     * @param bool               $pretty
716
-     * @param null               $date_or_time
717
-     * @return void
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidInterfaceException
720
-     * @throws InvalidDataTypeException
721
-     * @throws EE_Error
722
-     */
723
-    protected function _prepare_datetime_field(
724
-        EE_Datetime_Field $datetime_field,
725
-        $pretty = false,
726
-        $date_or_time = null
727
-    ) {
728
-        $datetime_field->set_timezone($this->_timezone);
729
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
-        // set the output returned
732
-        switch ($date_or_time) {
733
-            case 'D':
734
-                $datetime_field->set_date_time_output('date');
735
-                break;
736
-            case 'T':
737
-                $datetime_field->set_date_time_output('time');
738
-                break;
739
-            default:
740
-                $datetime_field->set_date_time_output();
741
-        }
742
-    }
743
-
744
-
745
-    /**
746
-     * This just takes care of clearing out the cached_properties
747
-     *
748
-     * @return void
749
-     */
750
-    protected function _clear_cached_properties()
751
-    {
752
-        $this->_cached_properties = array();
753
-    }
754
-
755
-
756
-    /**
757
-     * This just clears out ONE property if it exists in the cache
758
-     *
759
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
-     * @return void
761
-     */
762
-    protected function _clear_cached_property($property_name)
763
-    {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
766
-        }
767
-    }
768
-
769
-
770
-    /**
771
-     * Ensures that this related thing is a model object.
772
-     *
773
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
-     * @param string $model_name   name of the related thing, eg 'Attendee',
775
-     * @return EE_Base_Class
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
-    {
784
-        $other_model_instance = self::_get_model_instance_with_name(
785
-            self::_get_model_classname($model_name),
786
-            $this->_timezone
787
-        );
788
-        return $other_model_instance->ensure_is_obj($object_or_id);
789
-    }
790
-
791
-
792
-    /**
793
-     * Forgets the cached model of the given relation Name. So the next time we request it,
794
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
797
-     *
798
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
-     *                                                     Eg 'Registration'
800
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
-     *                                                     this is HasMany or HABTM.
805
-     * @throws ReflectionException
806
-     * @throws InvalidArgumentException
807
-     * @throws InvalidInterfaceException
808
-     * @throws InvalidDataTypeException
809
-     * @throws EE_Error
810
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
-     *                                                     relation from all
812
-     */
813
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
-    {
815
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
-        $index_in_cache = '';
817
-        if (! $relationship_to_model) {
818
-            throw new EE_Error(
819
-                sprintf(
820
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
-                    $relationName,
822
-                    get_class($this)
823
-                )
824
-            );
825
-        }
826
-        if ($clear_all) {
827
-            $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
829
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
832
-        } else {
833
-            if (
834
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
835
-                && $object_to_remove_or_index_into_array->ID()
836
-            ) {
837
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
838
-                if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
-                ) {
842
-                    $index_found_at = null;
843
-                    // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
-                        /** @noinspection TypeUnsafeComparisonInspection */
846
-                        if (
847
-                            $obj instanceof EE_Base_Class
848
-                            && (
849
-                                $obj == $object_to_remove_or_index_into_array
850
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
-                            )
852
-                        ) {
853
-                            $index_found_at = $index;
854
-                            break;
855
-                        }
856
-                    }
857
-                    if ($index_found_at) {
858
-                        $index_in_cache = $index_found_at;
859
-                    } else {
860
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
-                        // if it wasn't in it to begin with. So we're done
862
-                        return $object_to_remove_or_index_into_array;
863
-                    }
864
-                }
865
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
-                    /** @noinspection TypeUnsafeComparisonInspection */
869
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
-                        $index_in_cache = $index;
871
-                    }
872
-                }
873
-            } else {
874
-                $index_in_cache = $object_to_remove_or_index_into_array;
875
-            }
876
-            // supposedly we've found it. But it could just be that the client code
877
-            // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
-            } else {
882
-                // that thing was never cached anyways.
883
-                $obj_removed = null;
884
-            }
885
-        }
886
-        return $obj_removed;
887
-    }
888
-
889
-
890
-    /**
891
-     * update_cache_after_object_save
892
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
-     * obtained after being saved to the db
894
-     *
895
-     * @param string        $relationName       - the type of object that is cached
896
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
-     * @return boolean TRUE on success, FALSE on fail
899
-     * @throws ReflectionException
900
-     * @throws InvalidArgumentException
901
-     * @throws InvalidInterfaceException
902
-     * @throws InvalidDataTypeException
903
-     * @throws EE_Error
904
-     */
905
-    public function update_cache_after_object_save(
906
-        $relationName,
907
-        EE_Base_Class $newly_saved_object,
908
-        $current_cache_id = ''
909
-    ) {
910
-        // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
912
-        if ($newly_saved_object instanceof $obj_class) {
913
-            /* @type EE_Base_Class $newly_saved_object */
914
-            // now get the type of relation
915
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
-            // if this is a 1:1 relationship
917
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
-                // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
920
-                return true;
921
-                // or if it's some kind of sordid feral polyamorous relationship...
922
-            }
923
-            if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
-            ) {
927
-                // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
-                // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
-                return true;
932
-            }
933
-        }
934
-        return false;
935
-    }
936
-
937
-
938
-    /**
939
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
-     *
942
-     * @param string $relationName
943
-     * @return EE_Base_Class
944
-     */
945
-    public function get_one_from_cache($relationName)
946
-    {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
949
-            : null;
950
-        if (is_array($cached_array_or_object)) {
951
-            return array_shift($cached_array_or_object);
952
-        }
953
-        return $cached_array_or_object;
954
-    }
955
-
956
-
957
-    /**
958
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
-     *
961
-     * @param string $relationName
962
-     * @throws ReflectionException
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
-     */
969
-    public function get_all_from_cache($relationName)
970
-    {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects) ? $objects : array($objects);
974
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
-        // basically, if this model object was stored in the session, and these cached model objects
976
-        // already have IDs, let's make sure they're in their model's entity mapper
977
-        // otherwise we will have duplicates next time we call
978
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
-        $model = EE_Registry::instance()->load_model($relationName);
980
-        foreach ($objects as $model_object) {
981
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
-                if ($model_object->ID()) {
984
-                    $model->add_to_entity_map($model_object);
985
-                }
986
-            } else {
987
-                throw new EE_Error(
988
-                    sprintf(
989
-                        esc_html__(
990
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
-                            'event_espresso'
992
-                        ),
993
-                        $relationName,
994
-                        gettype($model_object)
995
-                    )
996
-                );
997
-            }
998
-        }
999
-        return $objects;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
-     * matching the given query conditions.
1006
-     *
1007
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1008
-     * @param int   $limit              How many objects to return.
1009
-     * @param array $query_params       Any additional conditions on the query.
1010
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
-     *                                  you can indicate just the columns you want returned
1012
-     * @return array|EE_Base_Class[]
1013
-     * @throws ReflectionException
1014
-     * @throws InvalidArgumentException
1015
-     * @throws InvalidInterfaceException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws EE_Error
1018
-     */
1019
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
-    {
1021
-        $model = $this->get_model();
1022
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
-            ? $model->get_primary_key_field()->get_name()
1024
-            : $field_to_order_by;
1025
-        $current_value = ! empty($field) ? $this->get($field) : null;
1026
-        if (empty($field) || empty($current_value)) {
1027
-            return array();
1028
-        }
1029
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
-     * matching the given query conditions.
1036
-     *
1037
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1038
-     * @param int   $limit              How many objects to return.
1039
-     * @param array $query_params       Any additional conditions on the query.
1040
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
-     *                                  you can indicate just the columns you want returned
1042
-     * @return array|EE_Base_Class[]
1043
-     * @throws ReflectionException
1044
-     * @throws InvalidArgumentException
1045
-     * @throws InvalidInterfaceException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws EE_Error
1048
-     */
1049
-    public function previous_x(
1050
-        $field_to_order_by = null,
1051
-        $limit = 1,
1052
-        $query_params = array(),
1053
-        $columns_to_select = null
1054
-    ) {
1055
-        $model = $this->get_model();
1056
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
-            ? $model->get_primary_key_field()->get_name()
1058
-            : $field_to_order_by;
1059
-        $current_value = ! empty($field) ? $this->get($field) : null;
1060
-        if (empty($field) || empty($current_value)) {
1061
-            return array();
1062
-        }
1063
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
-     * matching the given query conditions.
1070
-     *
1071
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1072
-     * @param array $query_params       Any additional conditions on the query.
1073
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
-     *                                  you can indicate just the columns you want returned
1075
-     * @return array|EE_Base_Class
1076
-     * @throws ReflectionException
1077
-     * @throws InvalidArgumentException
1078
-     * @throws InvalidInterfaceException
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws EE_Error
1081
-     */
1082
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
-    {
1084
-        $model = $this->get_model();
1085
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
-            ? $model->get_primary_key_field()->get_name()
1087
-            : $field_to_order_by;
1088
-        $current_value = ! empty($field) ? $this->get($field) : null;
1089
-        if (empty($field) || empty($current_value)) {
1090
-            return array();
1091
-        }
1092
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
-     * matching the given query conditions.
1099
-     *
1100
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1101
-     * @param array $query_params       Any additional conditions on the query.
1102
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
-     *                                  you can indicate just the column you want returned
1104
-     * @return array|EE_Base_Class
1105
-     * @throws ReflectionException
1106
-     * @throws InvalidArgumentException
1107
-     * @throws InvalidInterfaceException
1108
-     * @throws InvalidDataTypeException
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
-    {
1113
-        $model = $this->get_model();
1114
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
-            ? $model->get_primary_key_field()->get_name()
1116
-            : $field_to_order_by;
1117
-        $current_value = ! empty($field) ? $this->get($field) : null;
1118
-        if (empty($field) || empty($current_value)) {
1119
-            return array();
1120
-        }
1121
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     * Overrides parent because parent expects old models.
1127
-     * This also doesn't do any validation, and won't work for serialized arrays
1128
-     *
1129
-     * @param string $field_name
1130
-     * @param mixed  $field_value_from_db
1131
-     * @throws ReflectionException
1132
-     * @throws InvalidArgumentException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws InvalidDataTypeException
1135
-     * @throws EE_Error
1136
-     */
1137
-    public function set_from_db($field_name, $field_value_from_db)
1138
-    {
1139
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1140
-        if ($field_obj instanceof EE_Model_Field_Base) {
1141
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1142
-            // eg, a CPT model object could have an entry in the posts table, but no
1143
-            // entry in the meta table. Meaning that all its columns in the meta table
1144
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1145
-            if ($field_value_from_db === null) {
1146
-                if ($field_obj->is_nullable()) {
1147
-                    // if the field allows nulls, then let it be null
1148
-                    $field_value = null;
1149
-                } else {
1150
-                    $field_value = $field_obj->get_default_value();
1151
-                }
1152
-            } else {
1153
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
-            }
1155
-            $this->_fields[ $field_name ] = $field_value;
1156
-            $this->_clear_cached_property($field_name);
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * verifies that the specified field is of the correct type
1163
-     *
1164
-     * @param string $field_name
1165
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
-     *                                (in cases where the same property may be used for different outputs
1167
-     *                                - i.e. datetime, money etc.)
1168
-     * @return mixed
1169
-     * @throws ReflectionException
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidInterfaceException
1172
-     * @throws InvalidDataTypeException
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get($field_name, $extra_cache_ref = null)
1176
-    {
1177
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * This method simply returns the RAW unprocessed value for the given property in this class
1183
-     *
1184
-     * @param  string $field_name A valid fieldname
1185
-     * @return mixed              Whatever the raw value stored on the property is.
1186
-     * @throws ReflectionException
1187
-     * @throws InvalidArgumentException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws InvalidDataTypeException
1190
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
-     */
1192
-    public function get_raw($field_name)
1193
-    {
1194
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * This is used to return the internal DateTime object used for a field that is a
1203
-     * EE_Datetime_Field.
1204
-     *
1205
-     * @param string $field_name               The field name retrieving the DateTime object.
1206
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1208
-     *                                         EE_Datetime_Field and but the field value is null, then
1209
-     *                                         just null is returned (because that indicates that likely
1210
-     *                                         this field is nullable).
1211
-     * @throws InvalidArgumentException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws ReflectionException
1215
-     */
1216
-    public function get_DateTime_object($field_name)
1217
-    {
1218
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1220
-            EE_Error::add_error(
1221
-                sprintf(
1222
-                    esc_html__(
1223
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
-                        'event_espresso'
1225
-                    ),
1226
-                    $field_name
1227
-                ),
1228
-                __FILE__,
1229
-                __FUNCTION__,
1230
-                __LINE__
1231
-            );
1232
-            return false;
1233
-        }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1236
-            : null;
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * To be used in template to immediately echo out the value, and format it for output.
1242
-     * Eg, should call stripslashes and whatnot before echoing
1243
-     *
1244
-     * @param string $field_name      the name of the field as it appears in the DB
1245
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
-     *                                (in cases where the same property may be used for different outputs
1247
-     *                                - i.e. datetime, money etc.)
1248
-     * @return void
1249
-     * @throws ReflectionException
1250
-     * @throws InvalidArgumentException
1251
-     * @throws InvalidInterfaceException
1252
-     * @throws InvalidDataTypeException
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function e($field_name, $extra_cache_ref = null)
1256
-    {
1257
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
-     * can be easily used as the value of form input.
1264
-     *
1265
-     * @param string $field_name
1266
-     * @return void
1267
-     * @throws ReflectionException
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidInterfaceException
1270
-     * @throws InvalidDataTypeException
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function f($field_name)
1274
-    {
1275
-        $this->e($field_name, 'form_input');
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Same as `f()` but just returns the value instead of echoing it
1281
-     *
1282
-     * @param string $field_name
1283
-     * @return string
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function get_f($field_name)
1291
-    {
1292
-        return (string) $this->get_pretty($field_name, 'form_input');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
-     * to see what options are available.
1300
-     *
1301
-     * @param string $field_name
1302
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
-     *                                (in cases where the same property may be used for different outputs
1304
-     *                                - i.e. datetime, money etc.)
1305
-     * @return mixed
1306
-     * @throws ReflectionException
1307
-     * @throws InvalidArgumentException
1308
-     * @throws InvalidInterfaceException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function get_pretty($field_name, $extra_cache_ref = null)
1313
-    {
1314
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * This simply returns the datetime for the given field name
1320
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
-     * (and the equivalent e_date, e_time, e_datetime).
1322
-     *
1323
-     * @access   protected
1324
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
-     * @param string   $dt_frmt      valid datetime format used for date
1326
-     *                               (if '' then we just use the default on the field,
1327
-     *                               if NULL we use the last-used format)
1328
-     * @param string   $tm_frmt      Same as above except this is for time format
1329
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
-     *                               if field is not a valid dtt field, or void if echoing
1333
-     * @throws ReflectionException
1334
-     * @throws InvalidArgumentException
1335
-     * @throws InvalidInterfaceException
1336
-     * @throws InvalidDataTypeException
1337
-     * @throws EE_Error
1338
-     */
1339
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
-    {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($fieldname);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($fieldname);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
1772
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1800
-     *                                 if provided during the save() method (often client code will change the fields'
1801
-     *                                 values before calling save)
1802
-     * @return bool|int|string         1 on a successful update
1803
-     *                                 the ID of the new entry on insert
1804
-     *                                 0 on failure or if the model object isn't allowed to persist
1805
-     *                                 (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = null)
2194
-    {
2195
-        if (strpos($model_name, 'EE_') === 0) {
2196
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
-        } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2199
-        }
2200
-        return $model_classname;
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * returns the name of the primary key attribute
2206
-     *
2207
-     * @param null $classname
2208
-     * @throws ReflectionException
2209
-     * @throws InvalidArgumentException
2210
-     * @throws InvalidInterfaceException
2211
-     * @throws InvalidDataTypeException
2212
-     * @throws EE_Error
2213
-     * @return string
2214
-     */
2215
-    protected static function _get_primary_key_name($classname = null)
2216
-    {
2217
-        if (! $classname) {
2218
-            throw new EE_Error(
2219
-                sprintf(
2220
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
-                    $classname
2222
-                )
2223
-            );
2224
-        }
2225
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
-    }
2227
-
2228
-
2229
-    /**
2230
-     * Gets the value of the primary key.
2231
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
-     *
2235
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
-     * @throws ReflectionException
2237
-     * @throws InvalidArgumentException
2238
-     * @throws InvalidInterfaceException
2239
-     * @throws InvalidDataTypeException
2240
-     * @throws EE_Error
2241
-     */
2242
-    public function ID()
2243
-    {
2244
-        $model = $this->get_model();
2245
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2246
-        if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2248
-        }
2249
-        return $model->get_index_primary_key_string($this->_fields);
2250
-    }
2251
-
2252
-
2253
-    /**
2254
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2255
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2256
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2257
-     *
2258
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2259
-     * @param string $relationName                     eg 'Events','Question',etc.
2260
-     *                                                 an attendee to a group, you also want to specify which role they
2261
-     *                                                 will have in that group. So you would use this parameter to
2262
-     *                                                 specify array('role-column-name'=>'role-id')
2263
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2264
-     *                                                 allow you to further constrict the relation to being added.
2265
-     *                                                 However, keep in mind that the columns (keys) given must match a
2266
-     *                                                 column on the JOIN table and currently only the HABTM models
2267
-     *                                                 accept these additional conditions.  Also remember that if an
2268
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2269
-     *                                                 NEW row is created in the join table.
2270
-     * @param null   $cache_id
2271
-     * @throws ReflectionException
2272
-     * @throws InvalidArgumentException
2273
-     * @throws InvalidInterfaceException
2274
-     * @throws InvalidDataTypeException
2275
-     * @throws EE_Error
2276
-     * @return EE_Base_Class the object the relation was added to
2277
-     */
2278
-    public function _add_relation_to(
2279
-        $otherObjectModelObjectOrID,
2280
-        $relationName,
2281
-        $extra_join_model_fields_n_values = array(),
2282
-        $cache_id = null
2283
-    ) {
2284
-        $model = $this->get_model();
2285
-        // if this thing exists in the DB, save the relation to the DB
2286
-        if ($this->ID()) {
2287
-            $otherObject = $model->add_relationship_to(
2288
-                $this,
2289
-                $otherObjectModelObjectOrID,
2290
-                $relationName,
2291
-                $extra_join_model_fields_n_values
2292
-            );
2293
-            // clear cache so future get_many_related and get_first_related() return new results.
2294
-            $this->clear_cache($relationName, $otherObject, true);
2295
-            if ($otherObject instanceof EE_Base_Class) {
2296
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2297
-            }
2298
-        } else {
2299
-            // this thing doesn't exist in the DB,  so just cache it
2300
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2301
-                throw new EE_Error(
2302
-                    sprintf(
2303
-                        esc_html__(
2304
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2305
-                            'event_espresso'
2306
-                        ),
2307
-                        $otherObjectModelObjectOrID,
2308
-                        get_class($this)
2309
-                    )
2310
-                );
2311
-            }
2312
-            $otherObject = $otherObjectModelObjectOrID;
2313
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2314
-        }
2315
-        if ($otherObject instanceof EE_Base_Class) {
2316
-            // fix the reciprocal relation too
2317
-            if ($otherObject->ID()) {
2318
-                // its saved so assumed relations exist in the DB, so we can just
2319
-                // clear the cache so future queries use the updated info in the DB
2320
-                $otherObject->clear_cache(
2321
-                    $model->get_this_model_name(),
2322
-                    null,
2323
-                    true
2324
-                );
2325
-            } else {
2326
-                // it's not saved, so it caches relations like this
2327
-                $otherObject->cache($model->get_this_model_name(), $this);
2328
-            }
2329
-        }
2330
-        return $otherObject;
2331
-    }
2332
-
2333
-
2334
-    /**
2335
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2336
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2337
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2338
-     * from the cache
2339
-     *
2340
-     * @param mixed  $otherObjectModelObjectOrID
2341
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2342
-     *                to the DB yet
2343
-     * @param string $relationName
2344
-     * @param array  $where_query
2345
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2346
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2347
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2348
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2349
-     *                deleted.
2350
-     * @return EE_Base_Class the relation was removed from
2351
-     * @throws ReflectionException
2352
-     * @throws InvalidArgumentException
2353
-     * @throws InvalidInterfaceException
2354
-     * @throws InvalidDataTypeException
2355
-     * @throws EE_Error
2356
-     */
2357
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2358
-    {
2359
-        if ($this->ID()) {
2360
-            // if this exists in the DB, save the relation change to the DB too
2361
-            $otherObject = $this->get_model()->remove_relationship_to(
2362
-                $this,
2363
-                $otherObjectModelObjectOrID,
2364
-                $relationName,
2365
-                $where_query
2366
-            );
2367
-            $this->clear_cache(
2368
-                $relationName,
2369
-                $otherObject
2370
-            );
2371
-        } else {
2372
-            // this doesn't exist in the DB, just remove it from the cache
2373
-            $otherObject = $this->clear_cache(
2374
-                $relationName,
2375
-                $otherObjectModelObjectOrID
2376
-            );
2377
-        }
2378
-        if ($otherObject instanceof EE_Base_Class) {
2379
-            $otherObject->clear_cache(
2380
-                $this->get_model()->get_this_model_name(),
2381
-                $this
2382
-            );
2383
-        }
2384
-        return $otherObject;
2385
-    }
2386
-
2387
-
2388
-    /**
2389
-     * Removes ALL the related things for the $relationName.
2390
-     *
2391
-     * @param string $relationName
2392
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2393
-     * @return EE_Base_Class
2394
-     * @throws ReflectionException
2395
-     * @throws InvalidArgumentException
2396
-     * @throws InvalidInterfaceException
2397
-     * @throws InvalidDataTypeException
2398
-     * @throws EE_Error
2399
-     */
2400
-    public function _remove_relations($relationName, $where_query_params = array())
2401
-    {
2402
-        if ($this->ID()) {
2403
-            // if this exists in the DB, save the relation change to the DB too
2404
-            $otherObjects = $this->get_model()->remove_relations(
2405
-                $this,
2406
-                $relationName,
2407
-                $where_query_params
2408
-            );
2409
-            $this->clear_cache(
2410
-                $relationName,
2411
-                null,
2412
-                true
2413
-            );
2414
-        } else {
2415
-            // this doesn't exist in the DB, just remove it from the cache
2416
-            $otherObjects = $this->clear_cache(
2417
-                $relationName,
2418
-                null,
2419
-                true
2420
-            );
2421
-        }
2422
-        if (is_array($otherObjects)) {
2423
-            foreach ($otherObjects as $otherObject) {
2424
-                $otherObject->clear_cache(
2425
-                    $this->get_model()->get_this_model_name(),
2426
-                    $this
2427
-                );
2428
-            }
2429
-        }
2430
-        return $otherObjects;
2431
-    }
2432
-
2433
-
2434
-    /**
2435
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2436
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2437
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2438
-     * because we want to get even deleted items etc.
2439
-     *
2440
-     * @param string $relationName key in the model's _model_relations array
2441
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2442
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2443
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2444
-     *                             results if you want IDs
2445
-     * @throws ReflectionException
2446
-     * @throws InvalidArgumentException
2447
-     * @throws InvalidInterfaceException
2448
-     * @throws InvalidDataTypeException
2449
-     * @throws EE_Error
2450
-     */
2451
-    public function get_many_related($relationName, $query_params = array())
2452
-    {
2453
-        if ($this->ID()) {
2454
-            // this exists in the DB, so get the related things from either the cache or the DB
2455
-            // if there are query parameters, forget about caching the related model objects.
2456
-            if ($query_params) {
2457
-                $related_model_objects = $this->get_model()->get_all_related(
2458
-                    $this,
2459
-                    $relationName,
2460
-                    $query_params
2461
-                );
2462
-            } else {
2463
-                // did we already cache the result of this query?
2464
-                $cached_results = $this->get_all_from_cache($relationName);
2465
-                if (! $cached_results) {
2466
-                    $related_model_objects = $this->get_model()->get_all_related(
2467
-                        $this,
2468
-                        $relationName,
2469
-                        $query_params
2470
-                    );
2471
-                    // if no query parameters were passed, then we got all the related model objects
2472
-                    // for that relation. We can cache them then.
2473
-                    foreach ($related_model_objects as $related_model_object) {
2474
-                        $this->cache($relationName, $related_model_object);
2475
-                    }
2476
-                } else {
2477
-                    $related_model_objects = $cached_results;
2478
-                }
2479
-            }
2480
-        } else {
2481
-            // this doesn't exist in the DB, so just get the related things from the cache
2482
-            $related_model_objects = $this->get_all_from_cache($relationName);
2483
-        }
2484
-        return $related_model_objects;
2485
-    }
2486
-
2487
-
2488
-    /**
2489
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2490
-     * unless otherwise specified in the $query_params
2491
-     *
2492
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2493
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2494
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2495
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2496
-     *                               that by the setting $distinct to TRUE;
2497
-     * @return int
2498
-     * @throws ReflectionException
2499
-     * @throws InvalidArgumentException
2500
-     * @throws InvalidInterfaceException
2501
-     * @throws InvalidDataTypeException
2502
-     * @throws EE_Error
2503
-     */
2504
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2505
-    {
2506
-        return $this->get_model()->count_related(
2507
-            $this,
2508
-            $relation_name,
2509
-            $query_params,
2510
-            $field_to_count,
2511
-            $distinct
2512
-        );
2513
-    }
2514
-
2515
-
2516
-    /**
2517
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2518
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2519
-     *
2520
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2521
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2522
-     * @param string $field_to_sum  name of field to count by.
2523
-     *                              By default, uses primary key
2524
-     *                              (which doesn't make much sense, so you should probably change it)
2525
-     * @return int
2526
-     * @throws ReflectionException
2527
-     * @throws InvalidArgumentException
2528
-     * @throws InvalidInterfaceException
2529
-     * @throws InvalidDataTypeException
2530
-     * @throws EE_Error
2531
-     */
2532
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2533
-    {
2534
-        return $this->get_model()->sum_related(
2535
-            $this,
2536
-            $relation_name,
2537
-            $query_params,
2538
-            $field_to_sum
2539
-        );
2540
-    }
2541
-
2542
-
2543
-    /**
2544
-     * Gets the first (ie, one) related model object of the specified type.
2545
-     *
2546
-     * @param string $relationName key in the model's _model_relations array
2547
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2548
-     * @return EE_Base_Class (not an array, a single object)
2549
-     * @throws ReflectionException
2550
-     * @throws InvalidArgumentException
2551
-     * @throws InvalidInterfaceException
2552
-     * @throws InvalidDataTypeException
2553
-     * @throws EE_Error
2554
-     */
2555
-    public function get_first_related($relationName, $query_params = array())
2556
-    {
2557
-        $model = $this->get_model();
2558
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2559
-            // if they've provided some query parameters, don't bother trying to cache the result
2560
-            // also make sure we're not caching the result of get_first_related
2561
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2562
-            if (
2563
-                $query_params
2564
-                || ! $model->related_settings_for($relationName)
2565
-                     instanceof
2566
-                     EE_Belongs_To_Relation
2567
-            ) {
2568
-                $related_model_object = $model->get_first_related(
2569
-                    $this,
2570
-                    $relationName,
2571
-                    $query_params
2572
-                );
2573
-            } else {
2574
-                // first, check if we've already cached the result of this query
2575
-                $cached_result = $this->get_one_from_cache($relationName);
2576
-                if (! $cached_result) {
2577
-                    $related_model_object = $model->get_first_related(
2578
-                        $this,
2579
-                        $relationName,
2580
-                        $query_params
2581
-                    );
2582
-                    $this->cache($relationName, $related_model_object);
2583
-                } else {
2584
-                    $related_model_object = $cached_result;
2585
-                }
2586
-            }
2587
-        } else {
2588
-            $related_model_object = null;
2589
-            // this doesn't exist in the Db,
2590
-            // but maybe the relation is of type belongs to, and so the related thing might
2591
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2592
-                $related_model_object = $model->get_first_related(
2593
-                    $this,
2594
-                    $relationName,
2595
-                    $query_params
2596
-                );
2597
-            }
2598
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2599
-            // just get what's cached on this object
2600
-            if (! $related_model_object) {
2601
-                $related_model_object = $this->get_one_from_cache($relationName);
2602
-            }
2603
-        }
2604
-        return $related_model_object;
2605
-    }
2606
-
2607
-
2608
-    /**
2609
-     * Does a delete on all related objects of type $relationName and removes
2610
-     * the current model object's relation to them. If they can't be deleted (because
2611
-     * of blocking related model objects) does nothing. If the related model objects are
2612
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2613
-     * If this model object doesn't exist yet in the DB, just removes its related things
2614
-     *
2615
-     * @param string $relationName
2616
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2617
-     * @return int how many deleted
2618
-     * @throws ReflectionException
2619
-     * @throws InvalidArgumentException
2620
-     * @throws InvalidInterfaceException
2621
-     * @throws InvalidDataTypeException
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function delete_related($relationName, $query_params = array())
2625
-    {
2626
-        if ($this->ID()) {
2627
-            $count = $this->get_model()->delete_related(
2628
-                $this,
2629
-                $relationName,
2630
-                $query_params
2631
-            );
2632
-        } else {
2633
-            $count = count($this->get_all_from_cache($relationName));
2634
-            $this->clear_cache($relationName, null, true);
2635
-        }
2636
-        return $count;
2637
-    }
2638
-
2639
-
2640
-    /**
2641
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2642
-     * the current model object's relation to them. If they can't be deleted (because
2643
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2644
-     * If the related thing isn't a soft-deletable model object, this function is identical
2645
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2646
-     *
2647
-     * @param string $relationName
2648
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
-     * @return int how many deleted (including those soft deleted)
2650
-     * @throws ReflectionException
2651
-     * @throws InvalidArgumentException
2652
-     * @throws InvalidInterfaceException
2653
-     * @throws InvalidDataTypeException
2654
-     * @throws EE_Error
2655
-     */
2656
-    public function delete_related_permanently($relationName, $query_params = array())
2657
-    {
2658
-        if ($this->ID()) {
2659
-            $count = $this->get_model()->delete_related_permanently(
2660
-                $this,
2661
-                $relationName,
2662
-                $query_params
2663
-            );
2664
-        } else {
2665
-            $count = count($this->get_all_from_cache($relationName));
2666
-        }
2667
-        $this->clear_cache($relationName, null, true);
2668
-        return $count;
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * is_set
2674
-     * Just a simple utility function children can use for checking if property exists
2675
-     *
2676
-     * @access  public
2677
-     * @param  string $field_name property to check
2678
-     * @return bool                              TRUE if existing,FALSE if not.
2679
-     */
2680
-    public function is_set($field_name)
2681
-    {
2682
-        return isset($this->_fields[ $field_name ]);
2683
-    }
2684
-
2685
-
2686
-    /**
2687
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2688
-     * EE_Error exception if they don't
2689
-     *
2690
-     * @param  mixed (string|array) $properties properties to check
2691
-     * @throws EE_Error
2692
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2693
-     */
2694
-    protected function _property_exists($properties)
2695
-    {
2696
-        foreach ((array) $properties as $property_name) {
2697
-            // first make sure this property exists
2698
-            if (! $this->_fields[ $property_name ]) {
2699
-                throw new EE_Error(
2700
-                    sprintf(
2701
-                        esc_html__(
2702
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2703
-                            'event_espresso'
2704
-                        ),
2705
-                        $property_name
2706
-                    )
2707
-                );
2708
-            }
2709
-        }
2710
-        return true;
2711
-    }
2712
-
2713
-
2714
-    /**
2715
-     * This simply returns an array of model fields for this object
2716
-     *
2717
-     * @return array
2718
-     * @throws ReflectionException
2719
-     * @throws InvalidArgumentException
2720
-     * @throws InvalidInterfaceException
2721
-     * @throws InvalidDataTypeException
2722
-     * @throws EE_Error
2723
-     */
2724
-    public function model_field_array()
2725
-    {
2726
-        $fields = $this->get_model()->field_settings(false);
2727
-        $properties = array();
2728
-        // remove prepended underscore
2729
-        foreach ($fields as $field_name => $settings) {
2730
-            $properties[ $field_name ] = $this->get($field_name);
2731
-        }
2732
-        return $properties;
2733
-    }
2734
-
2735
-
2736
-    /**
2737
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2738
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2739
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2740
-     * Instead of requiring a plugin to extend the EE_Base_Class
2741
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2742
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2743
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2744
-     * and accepts 2 arguments: the object on which the function was called,
2745
-     * and an array of the original arguments passed to the function.
2746
-     * Whatever their callback function returns will be returned by this function.
2747
-     * Example: in functions.php (or in a plugin):
2748
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2749
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2750
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2751
-     *          return $previousReturnValue.$returnString;
2752
-     *      }
2753
-     * require('EE_Answer.class.php');
2754
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2755
-     * echo $answer->my_callback('monkeys',100);
2756
-     * //will output "you called my_callback! and passed args:monkeys,100"
2757
-     *
2758
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2759
-     * @param array  $args       array of original arguments passed to the function
2760
-     * @throws EE_Error
2761
-     * @return mixed whatever the plugin which calls add_filter decides
2762
-     */
2763
-    public function __call($methodName, $args)
2764
-    {
2765
-        $className = get_class($this);
2766
-        $tagName = "FHEE__{$className}__{$methodName}";
2767
-        if (! has_filter($tagName)) {
2768
-            throw new EE_Error(
2769
-                sprintf(
2770
-                    esc_html__(
2771
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2772
-                        'event_espresso'
2773
-                    ),
2774
-                    $methodName,
2775
-                    $className,
2776
-                    $tagName
2777
-                )
2778
-            );
2779
-        }
2780
-        return apply_filters($tagName, null, $this, $args);
2781
-    }
2782
-
2783
-
2784
-    /**
2785
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2786
-     * A $previous_value can be specified in case there are many meta rows with the same key
2787
-     *
2788
-     * @param string $meta_key
2789
-     * @param mixed  $meta_value
2790
-     * @param mixed  $previous_value
2791
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2792
-     *                  NOTE: if the values haven't changed, returns 0
2793
-     * @throws InvalidArgumentException
2794
-     * @throws InvalidInterfaceException
2795
-     * @throws InvalidDataTypeException
2796
-     * @throws EE_Error
2797
-     * @throws ReflectionException
2798
-     */
2799
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2800
-    {
2801
-        $query_params = array(
2802
-            array(
2803
-                'EXM_key'  => $meta_key,
2804
-                'OBJ_ID'   => $this->ID(),
2805
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2806
-            ),
2807
-        );
2808
-        if ($previous_value !== null) {
2809
-            $query_params[0]['EXM_value'] = $meta_value;
2810
-        }
2811
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2812
-        if (! $existing_rows_like_that) {
2813
-            return $this->add_extra_meta($meta_key, $meta_value);
2814
-        }
2815
-        foreach ($existing_rows_like_that as $existing_row) {
2816
-            $existing_row->save(array('EXM_value' => $meta_value));
2817
-        }
2818
-        return count($existing_rows_like_that);
2819
-    }
2820
-
2821
-
2822
-    /**
2823
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2824
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2825
-     * extra meta row was entered, false if not
2826
-     *
2827
-     * @param string  $meta_key
2828
-     * @param mixed   $meta_value
2829
-     * @param boolean $unique
2830
-     * @return boolean
2831
-     * @throws InvalidArgumentException
2832
-     * @throws InvalidInterfaceException
2833
-     * @throws InvalidDataTypeException
2834
-     * @throws EE_Error
2835
-     * @throws ReflectionException
2836
-     * @throws ReflectionException
2837
-     */
2838
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2839
-    {
2840
-        if ($unique) {
2841
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2842
-                array(
2843
-                    array(
2844
-                        'EXM_key'  => $meta_key,
2845
-                        'OBJ_ID'   => $this->ID(),
2846
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2847
-                    ),
2848
-                )
2849
-            );
2850
-            if ($existing_extra_meta) {
2851
-                return false;
2852
-            }
2853
-        }
2854
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2855
-            array(
2856
-                'EXM_key'   => $meta_key,
2857
-                'EXM_value' => $meta_value,
2858
-                'OBJ_ID'    => $this->ID(),
2859
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2860
-            )
2861
-        );
2862
-        $new_extra_meta->save();
2863
-        return true;
2864
-    }
2865
-
2866
-
2867
-    /**
2868
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2869
-     * is specified, only deletes extra meta records with that value.
2870
-     *
2871
-     * @param string $meta_key
2872
-     * @param mixed  $meta_value
2873
-     * @return int number of extra meta rows deleted
2874
-     * @throws InvalidArgumentException
2875
-     * @throws InvalidInterfaceException
2876
-     * @throws InvalidDataTypeException
2877
-     * @throws EE_Error
2878
-     * @throws ReflectionException
2879
-     */
2880
-    public function delete_extra_meta($meta_key, $meta_value = null)
2881
-    {
2882
-        $query_params = array(
2883
-            array(
2884
-                'EXM_key'  => $meta_key,
2885
-                'OBJ_ID'   => $this->ID(),
2886
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2887
-            ),
2888
-        );
2889
-        if ($meta_value !== null) {
2890
-            $query_params[0]['EXM_value'] = $meta_value;
2891
-        }
2892
-        return EEM_Extra_Meta::instance()->delete($query_params);
2893
-    }
2894
-
2895
-
2896
-    /**
2897
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2898
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2899
-     * You can specify $default is case you haven't found the extra meta
2900
-     *
2901
-     * @param string  $meta_key
2902
-     * @param boolean $single
2903
-     * @param mixed   $default if we don't find anything, what should we return?
2904
-     * @return mixed single value if $single; array if ! $single
2905
-     * @throws ReflectionException
2906
-     * @throws InvalidArgumentException
2907
-     * @throws InvalidInterfaceException
2908
-     * @throws InvalidDataTypeException
2909
-     * @throws EE_Error
2910
-     */
2911
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2912
-    {
2913
-        if ($single) {
2914
-            $result = $this->get_first_related(
2915
-                'Extra_Meta',
2916
-                array(array('EXM_key' => $meta_key))
2917
-            );
2918
-            if ($result instanceof EE_Extra_Meta) {
2919
-                return $result->value();
2920
-            }
2921
-        } else {
2922
-            $results = $this->get_many_related(
2923
-                'Extra_Meta',
2924
-                array(array('EXM_key' => $meta_key))
2925
-            );
2926
-            if ($results) {
2927
-                $values = array();
2928
-                foreach ($results as $result) {
2929
-                    if ($result instanceof EE_Extra_Meta) {
2930
-                        $values[ $result->ID() ] = $result->value();
2931
-                    }
2932
-                }
2933
-                return $values;
2934
-            }
2935
-        }
2936
-        // if nothing discovered yet return default.
2937
-        return apply_filters(
2938
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2939
-            $default,
2940
-            $meta_key,
2941
-            $single,
2942
-            $this
2943
-        );
2944
-    }
2945
-
2946
-
2947
-    /**
2948
-     * Returns a simple array of all the extra meta associated with this model object.
2949
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2950
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2951
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2952
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2953
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2954
-     * finally the extra meta's value as each sub-value. (eg
2955
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2956
-     *
2957
-     * @param boolean $one_of_each_key
2958
-     * @return array
2959
-     * @throws ReflectionException
2960
-     * @throws InvalidArgumentException
2961
-     * @throws InvalidInterfaceException
2962
-     * @throws InvalidDataTypeException
2963
-     * @throws EE_Error
2964
-     */
2965
-    public function all_extra_meta_array($one_of_each_key = true)
2966
-    {
2967
-        $return_array = array();
2968
-        if ($one_of_each_key) {
2969
-            $extra_meta_objs = $this->get_many_related(
2970
-                'Extra_Meta',
2971
-                array('group_by' => 'EXM_key')
2972
-            );
2973
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2974
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2975
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2976
-                }
2977
-            }
2978
-        } else {
2979
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2980
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2981
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2982
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2983
-                        $return_array[ $extra_meta_obj->key() ] = array();
2984
-                    }
2985
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2986
-                }
2987
-            }
2988
-        }
2989
-        return $return_array;
2990
-    }
2991
-
2992
-
2993
-    /**
2994
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2995
-     *
2996
-     * @return string
2997
-     * @throws ReflectionException
2998
-     * @throws InvalidArgumentException
2999
-     * @throws InvalidInterfaceException
3000
-     * @throws InvalidDataTypeException
3001
-     * @throws EE_Error
3002
-     */
3003
-    public function name()
3004
-    {
3005
-        // find a field that's not a text field
3006
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3007
-        if ($field_we_can_use) {
3008
-            return $this->get($field_we_can_use->get_name());
3009
-        }
3010
-        $first_few_properties = $this->model_field_array();
3011
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3012
-        $name_parts = array();
3013
-        foreach ($first_few_properties as $name => $value) {
3014
-            $name_parts[] = "$name:$value";
3015
-        }
3016
-        return implode(',', $name_parts);
3017
-    }
3018
-
3019
-
3020
-    /**
3021
-     * in_entity_map
3022
-     * Checks if this model object has been proven to already be in the entity map
3023
-     *
3024
-     * @return boolean
3025
-     * @throws ReflectionException
3026
-     * @throws InvalidArgumentException
3027
-     * @throws InvalidInterfaceException
3028
-     * @throws InvalidDataTypeException
3029
-     * @throws EE_Error
3030
-     */
3031
-    public function in_entity_map()
3032
-    {
3033
-        // well, if we looked, did we find it in the entity map?
3034
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3035
-    }
3036
-
3037
-
3038
-    /**
3039
-     * refresh_from_db
3040
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3041
-     *
3042
-     * @throws ReflectionException
3043
-     * @throws InvalidArgumentException
3044
-     * @throws InvalidInterfaceException
3045
-     * @throws InvalidDataTypeException
3046
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3047
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3048
-     */
3049
-    public function refresh_from_db()
3050
-    {
3051
-        if ($this->ID() && $this->in_entity_map()) {
3052
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3053
-        } else {
3054
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3055
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3056
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3057
-            // absolutely nothing in it for this ID
3058
-            if (WP_DEBUG) {
3059
-                throw new EE_Error(
3060
-                    sprintf(
3061
-                        esc_html__(
3062
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3063
-                            'event_espresso'
3064
-                        ),
3065
-                        $this->ID(),
3066
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3067
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3068
-                    )
3069
-                );
3070
-            }
3071
-        }
3072
-    }
3073
-
3074
-
3075
-    /**
3076
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3077
-     *
3078
-     * @since 4.9.80.p
3079
-     * @param EE_Model_Field_Base[] $fields
3080
-     * @param string $new_value_sql
3081
-     *      example: 'column_name=123',
3082
-     *      or 'column_name=column_name+1',
3083
-     *      or 'column_name= CASE
3084
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3085
-     *          THEN `column_name` + 5
3086
-     *          ELSE `column_name`
3087
-     *      END'
3088
-     *      Also updates $field on this model object with the latest value from the database.
3089
-     * @return bool
3090
-     * @throws EE_Error
3091
-     * @throws InvalidArgumentException
3092
-     * @throws InvalidDataTypeException
3093
-     * @throws InvalidInterfaceException
3094
-     * @throws ReflectionException
3095
-     */
3096
-    protected function updateFieldsInDB($fields, $new_value_sql)
3097
-    {
3098
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3099
-        // if it wasn't even there to start off.
3100
-        if (! $this->ID()) {
3101
-            $this->save();
3102
-        }
3103
-        global $wpdb;
3104
-        if (empty($fields)) {
3105
-            throw new InvalidArgumentException(
3106
-                esc_html__(
3107
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3108
-                    'event_espresso'
3109
-                )
3110
-            );
3111
-        }
3112
-        $first_field = reset($fields);
3113
-        $table_alias = $first_field->get_table_alias();
3114
-        foreach ($fields as $field) {
3115
-            if ($table_alias !== $field->get_table_alias()) {
3116
-                throw new InvalidArgumentException(
3117
-                    sprintf(
3118
-                        esc_html__(
3119
-                            // @codingStandardsIgnoreStart
3120
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3121
-                            // @codingStandardsIgnoreEnd
3122
-                            'event_espresso'
3123
-                        ),
3124
-                        $table_alias,
3125
-                        $field->get_table_alias()
3126
-                    )
3127
-                );
3128
-            }
3129
-        }
3130
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3131
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3132
-        $table_pk_value = $this->ID();
3133
-        $table_name = $table_obj->get_table_name();
3134
-        if ($table_obj instanceof EE_Secondary_Table) {
3135
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3136
-        } else {
3137
-            $table_pk_field_name = $table_obj->get_pk_column();
3138
-        }
3139
-
3140
-        $query =
3141
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		$value = $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+		return $value;
708
+	}
709
+
710
+
711
+	/**
712
+	 * set timezone, formats, and output for EE_Datetime_Field objects
713
+	 *
714
+	 * @param \EE_Datetime_Field $datetime_field
715
+	 * @param bool               $pretty
716
+	 * @param null               $date_or_time
717
+	 * @return void
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidInterfaceException
720
+	 * @throws InvalidDataTypeException
721
+	 * @throws EE_Error
722
+	 */
723
+	protected function _prepare_datetime_field(
724
+		EE_Datetime_Field $datetime_field,
725
+		$pretty = false,
726
+		$date_or_time = null
727
+	) {
728
+		$datetime_field->set_timezone($this->_timezone);
729
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
+		// set the output returned
732
+		switch ($date_or_time) {
733
+			case 'D':
734
+				$datetime_field->set_date_time_output('date');
735
+				break;
736
+			case 'T':
737
+				$datetime_field->set_date_time_output('time');
738
+				break;
739
+			default:
740
+				$datetime_field->set_date_time_output();
741
+		}
742
+	}
743
+
744
+
745
+	/**
746
+	 * This just takes care of clearing out the cached_properties
747
+	 *
748
+	 * @return void
749
+	 */
750
+	protected function _clear_cached_properties()
751
+	{
752
+		$this->_cached_properties = array();
753
+	}
754
+
755
+
756
+	/**
757
+	 * This just clears out ONE property if it exists in the cache
758
+	 *
759
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
+	 * @return void
761
+	 */
762
+	protected function _clear_cached_property($property_name)
763
+	{
764
+		if (isset($this->_cached_properties[ $property_name ])) {
765
+			unset($this->_cached_properties[ $property_name ]);
766
+		}
767
+	}
768
+
769
+
770
+	/**
771
+	 * Ensures that this related thing is a model object.
772
+	 *
773
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
775
+	 * @return EE_Base_Class
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
+	{
784
+		$other_model_instance = self::_get_model_instance_with_name(
785
+			self::_get_model_classname($model_name),
786
+			$this->_timezone
787
+		);
788
+		return $other_model_instance->ensure_is_obj($object_or_id);
789
+	}
790
+
791
+
792
+	/**
793
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
794
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
797
+	 *
798
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
+	 *                                                     Eg 'Registration'
800
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
+	 *                                                     this is HasMany or HABTM.
805
+	 * @throws ReflectionException
806
+	 * @throws InvalidArgumentException
807
+	 * @throws InvalidInterfaceException
808
+	 * @throws InvalidDataTypeException
809
+	 * @throws EE_Error
810
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
+	 *                                                     relation from all
812
+	 */
813
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
+	{
815
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
+		$index_in_cache = '';
817
+		if (! $relationship_to_model) {
818
+			throw new EE_Error(
819
+				sprintf(
820
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
+					$relationName,
822
+					get_class($this)
823
+				)
824
+			);
825
+		}
826
+		if ($clear_all) {
827
+			$obj_removed = true;
828
+			$this->_model_relations[ $relationName ] = null;
829
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
+			$obj_removed = $this->_model_relations[ $relationName ];
831
+			$this->_model_relations[ $relationName ] = null;
832
+		} else {
833
+			if (
834
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
835
+				&& $object_to_remove_or_index_into_array->ID()
836
+			) {
837
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
838
+				if (
839
+					is_array($this->_model_relations[ $relationName ])
840
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
+				) {
842
+					$index_found_at = null;
843
+					// find this object in the array even though it has a different key
844
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
+						/** @noinspection TypeUnsafeComparisonInspection */
846
+						if (
847
+							$obj instanceof EE_Base_Class
848
+							&& (
849
+								$obj == $object_to_remove_or_index_into_array
850
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
+							)
852
+						) {
853
+							$index_found_at = $index;
854
+							break;
855
+						}
856
+					}
857
+					if ($index_found_at) {
858
+						$index_in_cache = $index_found_at;
859
+					} else {
860
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
+						// if it wasn't in it to begin with. So we're done
862
+						return $object_to_remove_or_index_into_array;
863
+					}
864
+				}
865
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
+					/** @noinspection TypeUnsafeComparisonInspection */
869
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
+						$index_in_cache = $index;
871
+					}
872
+				}
873
+			} else {
874
+				$index_in_cache = $object_to_remove_or_index_into_array;
875
+			}
876
+			// supposedly we've found it. But it could just be that the client code
877
+			// provided a bad index/object
878
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
+			} else {
882
+				// that thing was never cached anyways.
883
+				$obj_removed = null;
884
+			}
885
+		}
886
+		return $obj_removed;
887
+	}
888
+
889
+
890
+	/**
891
+	 * update_cache_after_object_save
892
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
+	 * obtained after being saved to the db
894
+	 *
895
+	 * @param string        $relationName       - the type of object that is cached
896
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
+	 * @return boolean TRUE on success, FALSE on fail
899
+	 * @throws ReflectionException
900
+	 * @throws InvalidArgumentException
901
+	 * @throws InvalidInterfaceException
902
+	 * @throws InvalidDataTypeException
903
+	 * @throws EE_Error
904
+	 */
905
+	public function update_cache_after_object_save(
906
+		$relationName,
907
+		EE_Base_Class $newly_saved_object,
908
+		$current_cache_id = ''
909
+	) {
910
+		// verify that incoming object is of the correct type
911
+		$obj_class = 'EE_' . $relationName;
912
+		if ($newly_saved_object instanceof $obj_class) {
913
+			/* @type EE_Base_Class $newly_saved_object */
914
+			// now get the type of relation
915
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
+			// if this is a 1:1 relationship
917
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
+				// then just replace the cached object with the newly saved object
919
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
920
+				return true;
921
+				// or if it's some kind of sordid feral polyamorous relationship...
922
+			}
923
+			if (
924
+				is_array($this->_model_relations[ $relationName ])
925
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
+			) {
927
+				// then remove the current cached item
928
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
+				// and cache the newly saved object using it's new ID
930
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
+				return true;
932
+			}
933
+		}
934
+		return false;
935
+	}
936
+
937
+
938
+	/**
939
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
+	 *
942
+	 * @param string $relationName
943
+	 * @return EE_Base_Class
944
+	 */
945
+	public function get_one_from_cache($relationName)
946
+	{
947
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
+			? $this->_model_relations[ $relationName ]
949
+			: null;
950
+		if (is_array($cached_array_or_object)) {
951
+			return array_shift($cached_array_or_object);
952
+		}
953
+		return $cached_array_or_object;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
+	 *
961
+	 * @param string $relationName
962
+	 * @throws ReflectionException
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
+	 */
969
+	public function get_all_from_cache($relationName)
970
+	{
971
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects) ? $objects : array($objects);
974
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
+		// basically, if this model object was stored in the session, and these cached model objects
976
+		// already have IDs, let's make sure they're in their model's entity mapper
977
+		// otherwise we will have duplicates next time we call
978
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
+		$model = EE_Registry::instance()->load_model($relationName);
980
+		foreach ($objects as $model_object) {
981
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
+				if ($model_object->ID()) {
984
+					$model->add_to_entity_map($model_object);
985
+				}
986
+			} else {
987
+				throw new EE_Error(
988
+					sprintf(
989
+						esc_html__(
990
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
+							'event_espresso'
992
+						),
993
+						$relationName,
994
+						gettype($model_object)
995
+					)
996
+				);
997
+			}
998
+		}
999
+		return $objects;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
+	 * matching the given query conditions.
1006
+	 *
1007
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1008
+	 * @param int   $limit              How many objects to return.
1009
+	 * @param array $query_params       Any additional conditions on the query.
1010
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
+	 *                                  you can indicate just the columns you want returned
1012
+	 * @return array|EE_Base_Class[]
1013
+	 * @throws ReflectionException
1014
+	 * @throws InvalidArgumentException
1015
+	 * @throws InvalidInterfaceException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws EE_Error
1018
+	 */
1019
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
+	{
1021
+		$model = $this->get_model();
1022
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
+			? $model->get_primary_key_field()->get_name()
1024
+			: $field_to_order_by;
1025
+		$current_value = ! empty($field) ? $this->get($field) : null;
1026
+		if (empty($field) || empty($current_value)) {
1027
+			return array();
1028
+		}
1029
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
+	 * matching the given query conditions.
1036
+	 *
1037
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1038
+	 * @param int   $limit              How many objects to return.
1039
+	 * @param array $query_params       Any additional conditions on the query.
1040
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
+	 *                                  you can indicate just the columns you want returned
1042
+	 * @return array|EE_Base_Class[]
1043
+	 * @throws ReflectionException
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws InvalidInterfaceException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws EE_Error
1048
+	 */
1049
+	public function previous_x(
1050
+		$field_to_order_by = null,
1051
+		$limit = 1,
1052
+		$query_params = array(),
1053
+		$columns_to_select = null
1054
+	) {
1055
+		$model = $this->get_model();
1056
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
+			? $model->get_primary_key_field()->get_name()
1058
+			: $field_to_order_by;
1059
+		$current_value = ! empty($field) ? $this->get($field) : null;
1060
+		if (empty($field) || empty($current_value)) {
1061
+			return array();
1062
+		}
1063
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
+	 * matching the given query conditions.
1070
+	 *
1071
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1072
+	 * @param array $query_params       Any additional conditions on the query.
1073
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
+	 *                                  you can indicate just the columns you want returned
1075
+	 * @return array|EE_Base_Class
1076
+	 * @throws ReflectionException
1077
+	 * @throws InvalidArgumentException
1078
+	 * @throws InvalidInterfaceException
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws EE_Error
1081
+	 */
1082
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
+	{
1084
+		$model = $this->get_model();
1085
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
+			? $model->get_primary_key_field()->get_name()
1087
+			: $field_to_order_by;
1088
+		$current_value = ! empty($field) ? $this->get($field) : null;
1089
+		if (empty($field) || empty($current_value)) {
1090
+			return array();
1091
+		}
1092
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
+	 * matching the given query conditions.
1099
+	 *
1100
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1101
+	 * @param array $query_params       Any additional conditions on the query.
1102
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
+	 *                                  you can indicate just the column you want returned
1104
+	 * @return array|EE_Base_Class
1105
+	 * @throws ReflectionException
1106
+	 * @throws InvalidArgumentException
1107
+	 * @throws InvalidInterfaceException
1108
+	 * @throws InvalidDataTypeException
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
+	{
1113
+		$model = $this->get_model();
1114
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
+			? $model->get_primary_key_field()->get_name()
1116
+			: $field_to_order_by;
1117
+		$current_value = ! empty($field) ? $this->get($field) : null;
1118
+		if (empty($field) || empty($current_value)) {
1119
+			return array();
1120
+		}
1121
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 * Overrides parent because parent expects old models.
1127
+	 * This also doesn't do any validation, and won't work for serialized arrays
1128
+	 *
1129
+	 * @param string $field_name
1130
+	 * @param mixed  $field_value_from_db
1131
+	 * @throws ReflectionException
1132
+	 * @throws InvalidArgumentException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws InvalidDataTypeException
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	public function set_from_db($field_name, $field_value_from_db)
1138
+	{
1139
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1140
+		if ($field_obj instanceof EE_Model_Field_Base) {
1141
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1142
+			// eg, a CPT model object could have an entry in the posts table, but no
1143
+			// entry in the meta table. Meaning that all its columns in the meta table
1144
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1145
+			if ($field_value_from_db === null) {
1146
+				if ($field_obj->is_nullable()) {
1147
+					// if the field allows nulls, then let it be null
1148
+					$field_value = null;
1149
+				} else {
1150
+					$field_value = $field_obj->get_default_value();
1151
+				}
1152
+			} else {
1153
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
+			}
1155
+			$this->_fields[ $field_name ] = $field_value;
1156
+			$this->_clear_cached_property($field_name);
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * verifies that the specified field is of the correct type
1163
+	 *
1164
+	 * @param string $field_name
1165
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
+	 *                                (in cases where the same property may be used for different outputs
1167
+	 *                                - i.e. datetime, money etc.)
1168
+	 * @return mixed
1169
+	 * @throws ReflectionException
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidInterfaceException
1172
+	 * @throws InvalidDataTypeException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get($field_name, $extra_cache_ref = null)
1176
+	{
1177
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1183
+	 *
1184
+	 * @param  string $field_name A valid fieldname
1185
+	 * @return mixed              Whatever the raw value stored on the property is.
1186
+	 * @throws ReflectionException
1187
+	 * @throws InvalidArgumentException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws InvalidDataTypeException
1190
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
+	 */
1192
+	public function get_raw($field_name)
1193
+	{
1194
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1195
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
+			? $this->_fields[ $field_name ]->format('U')
1197
+			: $this->_fields[ $field_name ];
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * This is used to return the internal DateTime object used for a field that is a
1203
+	 * EE_Datetime_Field.
1204
+	 *
1205
+	 * @param string $field_name               The field name retrieving the DateTime object.
1206
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1208
+	 *                                         EE_Datetime_Field and but the field value is null, then
1209
+	 *                                         just null is returned (because that indicates that likely
1210
+	 *                                         this field is nullable).
1211
+	 * @throws InvalidArgumentException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws ReflectionException
1215
+	 */
1216
+	public function get_DateTime_object($field_name)
1217
+	{
1218
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1219
+		if (! $field_settings instanceof EE_Datetime_Field) {
1220
+			EE_Error::add_error(
1221
+				sprintf(
1222
+					esc_html__(
1223
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
+						'event_espresso'
1225
+					),
1226
+					$field_name
1227
+				),
1228
+				__FILE__,
1229
+				__FUNCTION__,
1230
+				__LINE__
1231
+			);
1232
+			return false;
1233
+		}
1234
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
+			? clone $this->_fields[ $field_name ]
1236
+			: null;
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * To be used in template to immediately echo out the value, and format it for output.
1242
+	 * Eg, should call stripslashes and whatnot before echoing
1243
+	 *
1244
+	 * @param string $field_name      the name of the field as it appears in the DB
1245
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
+	 *                                (in cases where the same property may be used for different outputs
1247
+	 *                                - i.e. datetime, money etc.)
1248
+	 * @return void
1249
+	 * @throws ReflectionException
1250
+	 * @throws InvalidArgumentException
1251
+	 * @throws InvalidInterfaceException
1252
+	 * @throws InvalidDataTypeException
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function e($field_name, $extra_cache_ref = null)
1256
+	{
1257
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
+	 * can be easily used as the value of form input.
1264
+	 *
1265
+	 * @param string $field_name
1266
+	 * @return void
1267
+	 * @throws ReflectionException
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidInterfaceException
1270
+	 * @throws InvalidDataTypeException
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function f($field_name)
1274
+	{
1275
+		$this->e($field_name, 'form_input');
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Same as `f()` but just returns the value instead of echoing it
1281
+	 *
1282
+	 * @param string $field_name
1283
+	 * @return string
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function get_f($field_name)
1291
+	{
1292
+		return (string) $this->get_pretty($field_name, 'form_input');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
+	 * to see what options are available.
1300
+	 *
1301
+	 * @param string $field_name
1302
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
+	 *                                (in cases where the same property may be used for different outputs
1304
+	 *                                - i.e. datetime, money etc.)
1305
+	 * @return mixed
1306
+	 * @throws ReflectionException
1307
+	 * @throws InvalidArgumentException
1308
+	 * @throws InvalidInterfaceException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function get_pretty($field_name, $extra_cache_ref = null)
1313
+	{
1314
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * This simply returns the datetime for the given field name
1320
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
+	 * (and the equivalent e_date, e_time, e_datetime).
1322
+	 *
1323
+	 * @access   protected
1324
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
+	 * @param string   $dt_frmt      valid datetime format used for date
1326
+	 *                               (if '' then we just use the default on the field,
1327
+	 *                               if NULL we use the last-used format)
1328
+	 * @param string   $tm_frmt      Same as above except this is for time format
1329
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
+	 *                               if field is not a valid dtt field, or void if echoing
1333
+	 * @throws ReflectionException
1334
+	 * @throws InvalidArgumentException
1335
+	 * @throws InvalidInterfaceException
1336
+	 * @throws InvalidDataTypeException
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
+	{
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($fieldname);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $fieldname ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $fieldname ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($fieldname);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
1772
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
+			if (! empty($this->_model_relations[ $relation_name ])) {
1774
+				$related_objects = $this->_model_relations[ $relation_name ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1800
+	 *                                 if provided during the save() method (often client code will change the fields'
1801
+	 *                                 values before calling save)
1802
+	 * @return bool|int|string         1 on a successful update
1803
+	 *                                 the ID of the new entry on insert
1804
+	 *                                 0 on failure or if the model object isn't allowed to persist
1805
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = null)
2194
+	{
2195
+		if (strpos($model_name, 'EE_') === 0) {
2196
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
+		} else {
2198
+			$model_classname = 'EEM_' . $model_name;
2199
+		}
2200
+		return $model_classname;
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * returns the name of the primary key attribute
2206
+	 *
2207
+	 * @param null $classname
2208
+	 * @throws ReflectionException
2209
+	 * @throws InvalidArgumentException
2210
+	 * @throws InvalidInterfaceException
2211
+	 * @throws InvalidDataTypeException
2212
+	 * @throws EE_Error
2213
+	 * @return string
2214
+	 */
2215
+	protected static function _get_primary_key_name($classname = null)
2216
+	{
2217
+		if (! $classname) {
2218
+			throw new EE_Error(
2219
+				sprintf(
2220
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
+					$classname
2222
+				)
2223
+			);
2224
+		}
2225
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
+	}
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the value of the primary key.
2231
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
+	 *
2235
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
+	 * @throws ReflectionException
2237
+	 * @throws InvalidArgumentException
2238
+	 * @throws InvalidInterfaceException
2239
+	 * @throws InvalidDataTypeException
2240
+	 * @throws EE_Error
2241
+	 */
2242
+	public function ID()
2243
+	{
2244
+		$model = $this->get_model();
2245
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2246
+		if ($model->has_primary_key_field()) {
2247
+			return $this->_fields[ $model->primary_key_name() ];
2248
+		}
2249
+		return $model->get_index_primary_key_string($this->_fields);
2250
+	}
2251
+
2252
+
2253
+	/**
2254
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2255
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2256
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2257
+	 *
2258
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2259
+	 * @param string $relationName                     eg 'Events','Question',etc.
2260
+	 *                                                 an attendee to a group, you also want to specify which role they
2261
+	 *                                                 will have in that group. So you would use this parameter to
2262
+	 *                                                 specify array('role-column-name'=>'role-id')
2263
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2264
+	 *                                                 allow you to further constrict the relation to being added.
2265
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2266
+	 *                                                 column on the JOIN table and currently only the HABTM models
2267
+	 *                                                 accept these additional conditions.  Also remember that if an
2268
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2269
+	 *                                                 NEW row is created in the join table.
2270
+	 * @param null   $cache_id
2271
+	 * @throws ReflectionException
2272
+	 * @throws InvalidArgumentException
2273
+	 * @throws InvalidInterfaceException
2274
+	 * @throws InvalidDataTypeException
2275
+	 * @throws EE_Error
2276
+	 * @return EE_Base_Class the object the relation was added to
2277
+	 */
2278
+	public function _add_relation_to(
2279
+		$otherObjectModelObjectOrID,
2280
+		$relationName,
2281
+		$extra_join_model_fields_n_values = array(),
2282
+		$cache_id = null
2283
+	) {
2284
+		$model = $this->get_model();
2285
+		// if this thing exists in the DB, save the relation to the DB
2286
+		if ($this->ID()) {
2287
+			$otherObject = $model->add_relationship_to(
2288
+				$this,
2289
+				$otherObjectModelObjectOrID,
2290
+				$relationName,
2291
+				$extra_join_model_fields_n_values
2292
+			);
2293
+			// clear cache so future get_many_related and get_first_related() return new results.
2294
+			$this->clear_cache($relationName, $otherObject, true);
2295
+			if ($otherObject instanceof EE_Base_Class) {
2296
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2297
+			}
2298
+		} else {
2299
+			// this thing doesn't exist in the DB,  so just cache it
2300
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2301
+				throw new EE_Error(
2302
+					sprintf(
2303
+						esc_html__(
2304
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2305
+							'event_espresso'
2306
+						),
2307
+						$otherObjectModelObjectOrID,
2308
+						get_class($this)
2309
+					)
2310
+				);
2311
+			}
2312
+			$otherObject = $otherObjectModelObjectOrID;
2313
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2314
+		}
2315
+		if ($otherObject instanceof EE_Base_Class) {
2316
+			// fix the reciprocal relation too
2317
+			if ($otherObject->ID()) {
2318
+				// its saved so assumed relations exist in the DB, so we can just
2319
+				// clear the cache so future queries use the updated info in the DB
2320
+				$otherObject->clear_cache(
2321
+					$model->get_this_model_name(),
2322
+					null,
2323
+					true
2324
+				);
2325
+			} else {
2326
+				// it's not saved, so it caches relations like this
2327
+				$otherObject->cache($model->get_this_model_name(), $this);
2328
+			}
2329
+		}
2330
+		return $otherObject;
2331
+	}
2332
+
2333
+
2334
+	/**
2335
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2336
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2337
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2338
+	 * from the cache
2339
+	 *
2340
+	 * @param mixed  $otherObjectModelObjectOrID
2341
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2342
+	 *                to the DB yet
2343
+	 * @param string $relationName
2344
+	 * @param array  $where_query
2345
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2346
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2347
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2348
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2349
+	 *                deleted.
2350
+	 * @return EE_Base_Class the relation was removed from
2351
+	 * @throws ReflectionException
2352
+	 * @throws InvalidArgumentException
2353
+	 * @throws InvalidInterfaceException
2354
+	 * @throws InvalidDataTypeException
2355
+	 * @throws EE_Error
2356
+	 */
2357
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2358
+	{
2359
+		if ($this->ID()) {
2360
+			// if this exists in the DB, save the relation change to the DB too
2361
+			$otherObject = $this->get_model()->remove_relationship_to(
2362
+				$this,
2363
+				$otherObjectModelObjectOrID,
2364
+				$relationName,
2365
+				$where_query
2366
+			);
2367
+			$this->clear_cache(
2368
+				$relationName,
2369
+				$otherObject
2370
+			);
2371
+		} else {
2372
+			// this doesn't exist in the DB, just remove it from the cache
2373
+			$otherObject = $this->clear_cache(
2374
+				$relationName,
2375
+				$otherObjectModelObjectOrID
2376
+			);
2377
+		}
2378
+		if ($otherObject instanceof EE_Base_Class) {
2379
+			$otherObject->clear_cache(
2380
+				$this->get_model()->get_this_model_name(),
2381
+				$this
2382
+			);
2383
+		}
2384
+		return $otherObject;
2385
+	}
2386
+
2387
+
2388
+	/**
2389
+	 * Removes ALL the related things for the $relationName.
2390
+	 *
2391
+	 * @param string $relationName
2392
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2393
+	 * @return EE_Base_Class
2394
+	 * @throws ReflectionException
2395
+	 * @throws InvalidArgumentException
2396
+	 * @throws InvalidInterfaceException
2397
+	 * @throws InvalidDataTypeException
2398
+	 * @throws EE_Error
2399
+	 */
2400
+	public function _remove_relations($relationName, $where_query_params = array())
2401
+	{
2402
+		if ($this->ID()) {
2403
+			// if this exists in the DB, save the relation change to the DB too
2404
+			$otherObjects = $this->get_model()->remove_relations(
2405
+				$this,
2406
+				$relationName,
2407
+				$where_query_params
2408
+			);
2409
+			$this->clear_cache(
2410
+				$relationName,
2411
+				null,
2412
+				true
2413
+			);
2414
+		} else {
2415
+			// this doesn't exist in the DB, just remove it from the cache
2416
+			$otherObjects = $this->clear_cache(
2417
+				$relationName,
2418
+				null,
2419
+				true
2420
+			);
2421
+		}
2422
+		if (is_array($otherObjects)) {
2423
+			foreach ($otherObjects as $otherObject) {
2424
+				$otherObject->clear_cache(
2425
+					$this->get_model()->get_this_model_name(),
2426
+					$this
2427
+				);
2428
+			}
2429
+		}
2430
+		return $otherObjects;
2431
+	}
2432
+
2433
+
2434
+	/**
2435
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2436
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2437
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2438
+	 * because we want to get even deleted items etc.
2439
+	 *
2440
+	 * @param string $relationName key in the model's _model_relations array
2441
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2442
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2443
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2444
+	 *                             results if you want IDs
2445
+	 * @throws ReflectionException
2446
+	 * @throws InvalidArgumentException
2447
+	 * @throws InvalidInterfaceException
2448
+	 * @throws InvalidDataTypeException
2449
+	 * @throws EE_Error
2450
+	 */
2451
+	public function get_many_related($relationName, $query_params = array())
2452
+	{
2453
+		if ($this->ID()) {
2454
+			// this exists in the DB, so get the related things from either the cache or the DB
2455
+			// if there are query parameters, forget about caching the related model objects.
2456
+			if ($query_params) {
2457
+				$related_model_objects = $this->get_model()->get_all_related(
2458
+					$this,
2459
+					$relationName,
2460
+					$query_params
2461
+				);
2462
+			} else {
2463
+				// did we already cache the result of this query?
2464
+				$cached_results = $this->get_all_from_cache($relationName);
2465
+				if (! $cached_results) {
2466
+					$related_model_objects = $this->get_model()->get_all_related(
2467
+						$this,
2468
+						$relationName,
2469
+						$query_params
2470
+					);
2471
+					// if no query parameters were passed, then we got all the related model objects
2472
+					// for that relation. We can cache them then.
2473
+					foreach ($related_model_objects as $related_model_object) {
2474
+						$this->cache($relationName, $related_model_object);
2475
+					}
2476
+				} else {
2477
+					$related_model_objects = $cached_results;
2478
+				}
2479
+			}
2480
+		} else {
2481
+			// this doesn't exist in the DB, so just get the related things from the cache
2482
+			$related_model_objects = $this->get_all_from_cache($relationName);
2483
+		}
2484
+		return $related_model_objects;
2485
+	}
2486
+
2487
+
2488
+	/**
2489
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2490
+	 * unless otherwise specified in the $query_params
2491
+	 *
2492
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2493
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2494
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2495
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2496
+	 *                               that by the setting $distinct to TRUE;
2497
+	 * @return int
2498
+	 * @throws ReflectionException
2499
+	 * @throws InvalidArgumentException
2500
+	 * @throws InvalidInterfaceException
2501
+	 * @throws InvalidDataTypeException
2502
+	 * @throws EE_Error
2503
+	 */
2504
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2505
+	{
2506
+		return $this->get_model()->count_related(
2507
+			$this,
2508
+			$relation_name,
2509
+			$query_params,
2510
+			$field_to_count,
2511
+			$distinct
2512
+		);
2513
+	}
2514
+
2515
+
2516
+	/**
2517
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2518
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2519
+	 *
2520
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2521
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2522
+	 * @param string $field_to_sum  name of field to count by.
2523
+	 *                              By default, uses primary key
2524
+	 *                              (which doesn't make much sense, so you should probably change it)
2525
+	 * @return int
2526
+	 * @throws ReflectionException
2527
+	 * @throws InvalidArgumentException
2528
+	 * @throws InvalidInterfaceException
2529
+	 * @throws InvalidDataTypeException
2530
+	 * @throws EE_Error
2531
+	 */
2532
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2533
+	{
2534
+		return $this->get_model()->sum_related(
2535
+			$this,
2536
+			$relation_name,
2537
+			$query_params,
2538
+			$field_to_sum
2539
+		);
2540
+	}
2541
+
2542
+
2543
+	/**
2544
+	 * Gets the first (ie, one) related model object of the specified type.
2545
+	 *
2546
+	 * @param string $relationName key in the model's _model_relations array
2547
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2548
+	 * @return EE_Base_Class (not an array, a single object)
2549
+	 * @throws ReflectionException
2550
+	 * @throws InvalidArgumentException
2551
+	 * @throws InvalidInterfaceException
2552
+	 * @throws InvalidDataTypeException
2553
+	 * @throws EE_Error
2554
+	 */
2555
+	public function get_first_related($relationName, $query_params = array())
2556
+	{
2557
+		$model = $this->get_model();
2558
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2559
+			// if they've provided some query parameters, don't bother trying to cache the result
2560
+			// also make sure we're not caching the result of get_first_related
2561
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2562
+			if (
2563
+				$query_params
2564
+				|| ! $model->related_settings_for($relationName)
2565
+					 instanceof
2566
+					 EE_Belongs_To_Relation
2567
+			) {
2568
+				$related_model_object = $model->get_first_related(
2569
+					$this,
2570
+					$relationName,
2571
+					$query_params
2572
+				);
2573
+			} else {
2574
+				// first, check if we've already cached the result of this query
2575
+				$cached_result = $this->get_one_from_cache($relationName);
2576
+				if (! $cached_result) {
2577
+					$related_model_object = $model->get_first_related(
2578
+						$this,
2579
+						$relationName,
2580
+						$query_params
2581
+					);
2582
+					$this->cache($relationName, $related_model_object);
2583
+				} else {
2584
+					$related_model_object = $cached_result;
2585
+				}
2586
+			}
2587
+		} else {
2588
+			$related_model_object = null;
2589
+			// this doesn't exist in the Db,
2590
+			// but maybe the relation is of type belongs to, and so the related thing might
2591
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2592
+				$related_model_object = $model->get_first_related(
2593
+					$this,
2594
+					$relationName,
2595
+					$query_params
2596
+				);
2597
+			}
2598
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2599
+			// just get what's cached on this object
2600
+			if (! $related_model_object) {
2601
+				$related_model_object = $this->get_one_from_cache($relationName);
2602
+			}
2603
+		}
2604
+		return $related_model_object;
2605
+	}
2606
+
2607
+
2608
+	/**
2609
+	 * Does a delete on all related objects of type $relationName and removes
2610
+	 * the current model object's relation to them. If they can't be deleted (because
2611
+	 * of blocking related model objects) does nothing. If the related model objects are
2612
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2613
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2614
+	 *
2615
+	 * @param string $relationName
2616
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2617
+	 * @return int how many deleted
2618
+	 * @throws ReflectionException
2619
+	 * @throws InvalidArgumentException
2620
+	 * @throws InvalidInterfaceException
2621
+	 * @throws InvalidDataTypeException
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function delete_related($relationName, $query_params = array())
2625
+	{
2626
+		if ($this->ID()) {
2627
+			$count = $this->get_model()->delete_related(
2628
+				$this,
2629
+				$relationName,
2630
+				$query_params
2631
+			);
2632
+		} else {
2633
+			$count = count($this->get_all_from_cache($relationName));
2634
+			$this->clear_cache($relationName, null, true);
2635
+		}
2636
+		return $count;
2637
+	}
2638
+
2639
+
2640
+	/**
2641
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2642
+	 * the current model object's relation to them. If they can't be deleted (because
2643
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2644
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2645
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2646
+	 *
2647
+	 * @param string $relationName
2648
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2649
+	 * @return int how many deleted (including those soft deleted)
2650
+	 * @throws ReflectionException
2651
+	 * @throws InvalidArgumentException
2652
+	 * @throws InvalidInterfaceException
2653
+	 * @throws InvalidDataTypeException
2654
+	 * @throws EE_Error
2655
+	 */
2656
+	public function delete_related_permanently($relationName, $query_params = array())
2657
+	{
2658
+		if ($this->ID()) {
2659
+			$count = $this->get_model()->delete_related_permanently(
2660
+				$this,
2661
+				$relationName,
2662
+				$query_params
2663
+			);
2664
+		} else {
2665
+			$count = count($this->get_all_from_cache($relationName));
2666
+		}
2667
+		$this->clear_cache($relationName, null, true);
2668
+		return $count;
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * is_set
2674
+	 * Just a simple utility function children can use for checking if property exists
2675
+	 *
2676
+	 * @access  public
2677
+	 * @param  string $field_name property to check
2678
+	 * @return bool                              TRUE if existing,FALSE if not.
2679
+	 */
2680
+	public function is_set($field_name)
2681
+	{
2682
+		return isset($this->_fields[ $field_name ]);
2683
+	}
2684
+
2685
+
2686
+	/**
2687
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2688
+	 * EE_Error exception if they don't
2689
+	 *
2690
+	 * @param  mixed (string|array) $properties properties to check
2691
+	 * @throws EE_Error
2692
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2693
+	 */
2694
+	protected function _property_exists($properties)
2695
+	{
2696
+		foreach ((array) $properties as $property_name) {
2697
+			// first make sure this property exists
2698
+			if (! $this->_fields[ $property_name ]) {
2699
+				throw new EE_Error(
2700
+					sprintf(
2701
+						esc_html__(
2702
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2703
+							'event_espresso'
2704
+						),
2705
+						$property_name
2706
+					)
2707
+				);
2708
+			}
2709
+		}
2710
+		return true;
2711
+	}
2712
+
2713
+
2714
+	/**
2715
+	 * This simply returns an array of model fields for this object
2716
+	 *
2717
+	 * @return array
2718
+	 * @throws ReflectionException
2719
+	 * @throws InvalidArgumentException
2720
+	 * @throws InvalidInterfaceException
2721
+	 * @throws InvalidDataTypeException
2722
+	 * @throws EE_Error
2723
+	 */
2724
+	public function model_field_array()
2725
+	{
2726
+		$fields = $this->get_model()->field_settings(false);
2727
+		$properties = array();
2728
+		// remove prepended underscore
2729
+		foreach ($fields as $field_name => $settings) {
2730
+			$properties[ $field_name ] = $this->get($field_name);
2731
+		}
2732
+		return $properties;
2733
+	}
2734
+
2735
+
2736
+	/**
2737
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2738
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2739
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2740
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2741
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2742
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2743
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2744
+	 * and accepts 2 arguments: the object on which the function was called,
2745
+	 * and an array of the original arguments passed to the function.
2746
+	 * Whatever their callback function returns will be returned by this function.
2747
+	 * Example: in functions.php (or in a plugin):
2748
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2749
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2750
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2751
+	 *          return $previousReturnValue.$returnString;
2752
+	 *      }
2753
+	 * require('EE_Answer.class.php');
2754
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2755
+	 * echo $answer->my_callback('monkeys',100);
2756
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2757
+	 *
2758
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2759
+	 * @param array  $args       array of original arguments passed to the function
2760
+	 * @throws EE_Error
2761
+	 * @return mixed whatever the plugin which calls add_filter decides
2762
+	 */
2763
+	public function __call($methodName, $args)
2764
+	{
2765
+		$className = get_class($this);
2766
+		$tagName = "FHEE__{$className}__{$methodName}";
2767
+		if (! has_filter($tagName)) {
2768
+			throw new EE_Error(
2769
+				sprintf(
2770
+					esc_html__(
2771
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2772
+						'event_espresso'
2773
+					),
2774
+					$methodName,
2775
+					$className,
2776
+					$tagName
2777
+				)
2778
+			);
2779
+		}
2780
+		return apply_filters($tagName, null, $this, $args);
2781
+	}
2782
+
2783
+
2784
+	/**
2785
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2786
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2787
+	 *
2788
+	 * @param string $meta_key
2789
+	 * @param mixed  $meta_value
2790
+	 * @param mixed  $previous_value
2791
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2792
+	 *                  NOTE: if the values haven't changed, returns 0
2793
+	 * @throws InvalidArgumentException
2794
+	 * @throws InvalidInterfaceException
2795
+	 * @throws InvalidDataTypeException
2796
+	 * @throws EE_Error
2797
+	 * @throws ReflectionException
2798
+	 */
2799
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2800
+	{
2801
+		$query_params = array(
2802
+			array(
2803
+				'EXM_key'  => $meta_key,
2804
+				'OBJ_ID'   => $this->ID(),
2805
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2806
+			),
2807
+		);
2808
+		if ($previous_value !== null) {
2809
+			$query_params[0]['EXM_value'] = $meta_value;
2810
+		}
2811
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2812
+		if (! $existing_rows_like_that) {
2813
+			return $this->add_extra_meta($meta_key, $meta_value);
2814
+		}
2815
+		foreach ($existing_rows_like_that as $existing_row) {
2816
+			$existing_row->save(array('EXM_value' => $meta_value));
2817
+		}
2818
+		return count($existing_rows_like_that);
2819
+	}
2820
+
2821
+
2822
+	/**
2823
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2824
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2825
+	 * extra meta row was entered, false if not
2826
+	 *
2827
+	 * @param string  $meta_key
2828
+	 * @param mixed   $meta_value
2829
+	 * @param boolean $unique
2830
+	 * @return boolean
2831
+	 * @throws InvalidArgumentException
2832
+	 * @throws InvalidInterfaceException
2833
+	 * @throws InvalidDataTypeException
2834
+	 * @throws EE_Error
2835
+	 * @throws ReflectionException
2836
+	 * @throws ReflectionException
2837
+	 */
2838
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2839
+	{
2840
+		if ($unique) {
2841
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2842
+				array(
2843
+					array(
2844
+						'EXM_key'  => $meta_key,
2845
+						'OBJ_ID'   => $this->ID(),
2846
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2847
+					),
2848
+				)
2849
+			);
2850
+			if ($existing_extra_meta) {
2851
+				return false;
2852
+			}
2853
+		}
2854
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2855
+			array(
2856
+				'EXM_key'   => $meta_key,
2857
+				'EXM_value' => $meta_value,
2858
+				'OBJ_ID'    => $this->ID(),
2859
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2860
+			)
2861
+		);
2862
+		$new_extra_meta->save();
2863
+		return true;
2864
+	}
2865
+
2866
+
2867
+	/**
2868
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2869
+	 * is specified, only deletes extra meta records with that value.
2870
+	 *
2871
+	 * @param string $meta_key
2872
+	 * @param mixed  $meta_value
2873
+	 * @return int number of extra meta rows deleted
2874
+	 * @throws InvalidArgumentException
2875
+	 * @throws InvalidInterfaceException
2876
+	 * @throws InvalidDataTypeException
2877
+	 * @throws EE_Error
2878
+	 * @throws ReflectionException
2879
+	 */
2880
+	public function delete_extra_meta($meta_key, $meta_value = null)
2881
+	{
2882
+		$query_params = array(
2883
+			array(
2884
+				'EXM_key'  => $meta_key,
2885
+				'OBJ_ID'   => $this->ID(),
2886
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2887
+			),
2888
+		);
2889
+		if ($meta_value !== null) {
2890
+			$query_params[0]['EXM_value'] = $meta_value;
2891
+		}
2892
+		return EEM_Extra_Meta::instance()->delete($query_params);
2893
+	}
2894
+
2895
+
2896
+	/**
2897
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2898
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2899
+	 * You can specify $default is case you haven't found the extra meta
2900
+	 *
2901
+	 * @param string  $meta_key
2902
+	 * @param boolean $single
2903
+	 * @param mixed   $default if we don't find anything, what should we return?
2904
+	 * @return mixed single value if $single; array if ! $single
2905
+	 * @throws ReflectionException
2906
+	 * @throws InvalidArgumentException
2907
+	 * @throws InvalidInterfaceException
2908
+	 * @throws InvalidDataTypeException
2909
+	 * @throws EE_Error
2910
+	 */
2911
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2912
+	{
2913
+		if ($single) {
2914
+			$result = $this->get_first_related(
2915
+				'Extra_Meta',
2916
+				array(array('EXM_key' => $meta_key))
2917
+			);
2918
+			if ($result instanceof EE_Extra_Meta) {
2919
+				return $result->value();
2920
+			}
2921
+		} else {
2922
+			$results = $this->get_many_related(
2923
+				'Extra_Meta',
2924
+				array(array('EXM_key' => $meta_key))
2925
+			);
2926
+			if ($results) {
2927
+				$values = array();
2928
+				foreach ($results as $result) {
2929
+					if ($result instanceof EE_Extra_Meta) {
2930
+						$values[ $result->ID() ] = $result->value();
2931
+					}
2932
+				}
2933
+				return $values;
2934
+			}
2935
+		}
2936
+		// if nothing discovered yet return default.
2937
+		return apply_filters(
2938
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2939
+			$default,
2940
+			$meta_key,
2941
+			$single,
2942
+			$this
2943
+		);
2944
+	}
2945
+
2946
+
2947
+	/**
2948
+	 * Returns a simple array of all the extra meta associated with this model object.
2949
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2950
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2951
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2952
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2953
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2954
+	 * finally the extra meta's value as each sub-value. (eg
2955
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2956
+	 *
2957
+	 * @param boolean $one_of_each_key
2958
+	 * @return array
2959
+	 * @throws ReflectionException
2960
+	 * @throws InvalidArgumentException
2961
+	 * @throws InvalidInterfaceException
2962
+	 * @throws InvalidDataTypeException
2963
+	 * @throws EE_Error
2964
+	 */
2965
+	public function all_extra_meta_array($one_of_each_key = true)
2966
+	{
2967
+		$return_array = array();
2968
+		if ($one_of_each_key) {
2969
+			$extra_meta_objs = $this->get_many_related(
2970
+				'Extra_Meta',
2971
+				array('group_by' => 'EXM_key')
2972
+			);
2973
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2974
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2975
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2976
+				}
2977
+			}
2978
+		} else {
2979
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2980
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2981
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2982
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2983
+						$return_array[ $extra_meta_obj->key() ] = array();
2984
+					}
2985
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2986
+				}
2987
+			}
2988
+		}
2989
+		return $return_array;
2990
+	}
2991
+
2992
+
2993
+	/**
2994
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2995
+	 *
2996
+	 * @return string
2997
+	 * @throws ReflectionException
2998
+	 * @throws InvalidArgumentException
2999
+	 * @throws InvalidInterfaceException
3000
+	 * @throws InvalidDataTypeException
3001
+	 * @throws EE_Error
3002
+	 */
3003
+	public function name()
3004
+	{
3005
+		// find a field that's not a text field
3006
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3007
+		if ($field_we_can_use) {
3008
+			return $this->get($field_we_can_use->get_name());
3009
+		}
3010
+		$first_few_properties = $this->model_field_array();
3011
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3012
+		$name_parts = array();
3013
+		foreach ($first_few_properties as $name => $value) {
3014
+			$name_parts[] = "$name:$value";
3015
+		}
3016
+		return implode(',', $name_parts);
3017
+	}
3018
+
3019
+
3020
+	/**
3021
+	 * in_entity_map
3022
+	 * Checks if this model object has been proven to already be in the entity map
3023
+	 *
3024
+	 * @return boolean
3025
+	 * @throws ReflectionException
3026
+	 * @throws InvalidArgumentException
3027
+	 * @throws InvalidInterfaceException
3028
+	 * @throws InvalidDataTypeException
3029
+	 * @throws EE_Error
3030
+	 */
3031
+	public function in_entity_map()
3032
+	{
3033
+		// well, if we looked, did we find it in the entity map?
3034
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3035
+	}
3036
+
3037
+
3038
+	/**
3039
+	 * refresh_from_db
3040
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3041
+	 *
3042
+	 * @throws ReflectionException
3043
+	 * @throws InvalidArgumentException
3044
+	 * @throws InvalidInterfaceException
3045
+	 * @throws InvalidDataTypeException
3046
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3047
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3048
+	 */
3049
+	public function refresh_from_db()
3050
+	{
3051
+		if ($this->ID() && $this->in_entity_map()) {
3052
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3053
+		} else {
3054
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3055
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3056
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3057
+			// absolutely nothing in it for this ID
3058
+			if (WP_DEBUG) {
3059
+				throw new EE_Error(
3060
+					sprintf(
3061
+						esc_html__(
3062
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3063
+							'event_espresso'
3064
+						),
3065
+						$this->ID(),
3066
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3067
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3068
+					)
3069
+				);
3070
+			}
3071
+		}
3072
+	}
3073
+
3074
+
3075
+	/**
3076
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3077
+	 *
3078
+	 * @since 4.9.80.p
3079
+	 * @param EE_Model_Field_Base[] $fields
3080
+	 * @param string $new_value_sql
3081
+	 *      example: 'column_name=123',
3082
+	 *      or 'column_name=column_name+1',
3083
+	 *      or 'column_name= CASE
3084
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3085
+	 *          THEN `column_name` + 5
3086
+	 *          ELSE `column_name`
3087
+	 *      END'
3088
+	 *      Also updates $field on this model object with the latest value from the database.
3089
+	 * @return bool
3090
+	 * @throws EE_Error
3091
+	 * @throws InvalidArgumentException
3092
+	 * @throws InvalidDataTypeException
3093
+	 * @throws InvalidInterfaceException
3094
+	 * @throws ReflectionException
3095
+	 */
3096
+	protected function updateFieldsInDB($fields, $new_value_sql)
3097
+	{
3098
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3099
+		// if it wasn't even there to start off.
3100
+		if (! $this->ID()) {
3101
+			$this->save();
3102
+		}
3103
+		global $wpdb;
3104
+		if (empty($fields)) {
3105
+			throw new InvalidArgumentException(
3106
+				esc_html__(
3107
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3108
+					'event_espresso'
3109
+				)
3110
+			);
3111
+		}
3112
+		$first_field = reset($fields);
3113
+		$table_alias = $first_field->get_table_alias();
3114
+		foreach ($fields as $field) {
3115
+			if ($table_alias !== $field->get_table_alias()) {
3116
+				throw new InvalidArgumentException(
3117
+					sprintf(
3118
+						esc_html__(
3119
+							// @codingStandardsIgnoreStart
3120
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3121
+							// @codingStandardsIgnoreEnd
3122
+							'event_espresso'
3123
+						),
3124
+						$table_alias,
3125
+						$field->get_table_alias()
3126
+					)
3127
+				);
3128
+			}
3129
+		}
3130
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3131
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3132
+		$table_pk_value = $this->ID();
3133
+		$table_name = $table_obj->get_table_name();
3134
+		if ($table_obj instanceof EE_Secondary_Table) {
3135
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3136
+		} else {
3137
+			$table_pk_field_name = $table_obj->get_pk_column();
3138
+		}
3139
+
3140
+		$query =
3141
+			"UPDATE `{$table_name}`
3142 3142
             SET "
3143
-            . $new_value_sql
3144
-            . $wpdb->prepare(
3145
-                "
3143
+			. $new_value_sql
3144
+			. $wpdb->prepare(
3145
+				"
3146 3146
             WHERE `{$table_pk_field_name}` = %d;",
3147
-                $table_pk_value
3148
-            );
3149
-        $result = $wpdb->query($query);
3150
-        foreach ($fields as $field) {
3151
-            // If it was successful, we'd like to know the new value.
3152
-            // If it failed, we'd also like to know the new value.
3153
-            $new_value = $this->get_model()->get_var(
3154
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3155
-                    $this->get_model()->get_index_primary_key_string(
3156
-                        $this->model_field_array()
3157
-                    ),
3158
-                    array(
3159
-                        'default_where_conditions' => 'minimum',
3160
-                    )
3161
-                ),
3162
-                $field->get_name()
3163
-            );
3164
-            $this->set_from_db(
3165
-                $field->get_name(),
3166
-                $new_value
3167
-            );
3168
-        }
3169
-        return (bool) $result;
3170
-    }
3171
-
3172
-
3173
-    /**
3174
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3175
-     * Does not allow negative values, however.
3176
-     *
3177
-     * @since 4.9.80.p
3178
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3179
-     *                                   (positive or negative). One important gotcha: all these values must be
3180
-     *                                   on the same table (eg don't pass in one field for the posts table and
3181
-     *                                   another for the event meta table.)
3182
-     * @return bool
3183
-     * @throws EE_Error
3184
-     * @throws InvalidArgumentException
3185
-     * @throws InvalidDataTypeException
3186
-     * @throws InvalidInterfaceException
3187
-     * @throws ReflectionException
3188
-     */
3189
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3190
-    {
3191
-        global $wpdb;
3192
-        if (empty($fields_n_quantities)) {
3193
-            // No fields to update? Well sure, we updated them to that value just fine.
3194
-            return true;
3195
-        }
3196
-        $fields = [];
3197
-        $set_sql_statements = [];
3198
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3199
-            $field = $this->get_model()->field_settings_for($field_name, true);
3200
-            $fields[] = $field;
3201
-            $column_name = $field->get_table_column();
3202
-
3203
-            $abs_qty = absint($quantity);
3204
-            if ($quantity > 0) {
3205
-                // don't let the value be negative as often these fields are unsigned
3206
-                $set_sql_statements[] = $wpdb->prepare(
3207
-                    "`{$column_name}` = `{$column_name}` + %d",
3208
-                    $abs_qty
3209
-                );
3210
-            } else {
3211
-                $set_sql_statements[] = $wpdb->prepare(
3212
-                    "`{$column_name}` = CASE
3147
+				$table_pk_value
3148
+			);
3149
+		$result = $wpdb->query($query);
3150
+		foreach ($fields as $field) {
3151
+			// If it was successful, we'd like to know the new value.
3152
+			// If it failed, we'd also like to know the new value.
3153
+			$new_value = $this->get_model()->get_var(
3154
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3155
+					$this->get_model()->get_index_primary_key_string(
3156
+						$this->model_field_array()
3157
+					),
3158
+					array(
3159
+						'default_where_conditions' => 'minimum',
3160
+					)
3161
+				),
3162
+				$field->get_name()
3163
+			);
3164
+			$this->set_from_db(
3165
+				$field->get_name(),
3166
+				$new_value
3167
+			);
3168
+		}
3169
+		return (bool) $result;
3170
+	}
3171
+
3172
+
3173
+	/**
3174
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3175
+	 * Does not allow negative values, however.
3176
+	 *
3177
+	 * @since 4.9.80.p
3178
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3179
+	 *                                   (positive or negative). One important gotcha: all these values must be
3180
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3181
+	 *                                   another for the event meta table.)
3182
+	 * @return bool
3183
+	 * @throws EE_Error
3184
+	 * @throws InvalidArgumentException
3185
+	 * @throws InvalidDataTypeException
3186
+	 * @throws InvalidInterfaceException
3187
+	 * @throws ReflectionException
3188
+	 */
3189
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3190
+	{
3191
+		global $wpdb;
3192
+		if (empty($fields_n_quantities)) {
3193
+			// No fields to update? Well sure, we updated them to that value just fine.
3194
+			return true;
3195
+		}
3196
+		$fields = [];
3197
+		$set_sql_statements = [];
3198
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3199
+			$field = $this->get_model()->field_settings_for($field_name, true);
3200
+			$fields[] = $field;
3201
+			$column_name = $field->get_table_column();
3202
+
3203
+			$abs_qty = absint($quantity);
3204
+			if ($quantity > 0) {
3205
+				// don't let the value be negative as often these fields are unsigned
3206
+				$set_sql_statements[] = $wpdb->prepare(
3207
+					"`{$column_name}` = `{$column_name}` + %d",
3208
+					$abs_qty
3209
+				);
3210
+			} else {
3211
+				$set_sql_statements[] = $wpdb->prepare(
3212
+					"`{$column_name}` = CASE
3213 3213
                        WHEN (`{$column_name}` >= %d)
3214 3214
                        THEN `{$column_name}` - %d
3215 3215
                        ELSE 0
3216 3216
                     END",
3217
-                    $abs_qty,
3218
-                    $abs_qty
3219
-                );
3220
-            }
3221
-        }
3222
-        return $this->updateFieldsInDB(
3223
-            $fields,
3224
-            implode(', ', $set_sql_statements)
3225
-        );
3226
-    }
3227
-
3228
-
3229
-    /**
3230
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3231
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3232
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3233
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3234
-     * Otherwise returns false.
3235
-     *
3236
-     * @since 4.9.80.p
3237
-     * @param string $field_name_to_bump
3238
-     * @param string $field_name_affecting_total
3239
-     * @param string $limit_field_name
3240
-     * @param int    $quantity
3241
-     * @return bool
3242
-     * @throws EE_Error
3243
-     * @throws InvalidArgumentException
3244
-     * @throws InvalidDataTypeException
3245
-     * @throws InvalidInterfaceException
3246
-     * @throws ReflectionException
3247
-     */
3248
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3249
-    {
3250
-        global $wpdb;
3251
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3252
-        $column_name = $field->get_table_column();
3253
-
3254
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3255
-        $column_affecting_total = $field_affecting_total->get_table_column();
3256
-
3257
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3258
-        $limiting_column = $limiting_field->get_table_column();
3259
-        return $this->updateFieldsInDB(
3260
-            [$field],
3261
-            $wpdb->prepare(
3262
-                "`{$column_name}` =
3217
+					$abs_qty,
3218
+					$abs_qty
3219
+				);
3220
+			}
3221
+		}
3222
+		return $this->updateFieldsInDB(
3223
+			$fields,
3224
+			implode(', ', $set_sql_statements)
3225
+		);
3226
+	}
3227
+
3228
+
3229
+	/**
3230
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3231
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3232
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3233
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3234
+	 * Otherwise returns false.
3235
+	 *
3236
+	 * @since 4.9.80.p
3237
+	 * @param string $field_name_to_bump
3238
+	 * @param string $field_name_affecting_total
3239
+	 * @param string $limit_field_name
3240
+	 * @param int    $quantity
3241
+	 * @return bool
3242
+	 * @throws EE_Error
3243
+	 * @throws InvalidArgumentException
3244
+	 * @throws InvalidDataTypeException
3245
+	 * @throws InvalidInterfaceException
3246
+	 * @throws ReflectionException
3247
+	 */
3248
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3249
+	{
3250
+		global $wpdb;
3251
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3252
+		$column_name = $field->get_table_column();
3253
+
3254
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3255
+		$column_affecting_total = $field_affecting_total->get_table_column();
3256
+
3257
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3258
+		$limiting_column = $limiting_field->get_table_column();
3259
+		return $this->updateFieldsInDB(
3260
+			[$field],
3261
+			$wpdb->prepare(
3262
+				"`{$column_name}` =
3263 3263
             CASE
3264 3264
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3265 3265
                THEN `{$column_name}` + %d
3266 3266
                ELSE `{$column_name}`
3267 3267
             END",
3268
-                $quantity,
3269
-                EE_INF_IN_DB,
3270
-                $quantity
3271
-            )
3272
-        );
3273
-    }
3274
-
3275
-
3276
-    /**
3277
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3278
-     * (probably a bad assumption they have made, oh well)
3279
-     *
3280
-     * @return string
3281
-     */
3282
-    public function __toString()
3283
-    {
3284
-        try {
3285
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3286
-        } catch (Exception $e) {
3287
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3288
-            return '';
3289
-        }
3290
-    }
3291
-
3292
-
3293
-    /**
3294
-     * Clear related model objects if they're already in the DB, because otherwise when we
3295
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3296
-     * This means if we have made changes to those related model objects, and want to unserialize
3297
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3298
-     * Instead, those related model objects should be directly serialized and stored.
3299
-     * Eg, the following won't work:
3300
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
-     * $att = $reg->attendee();
3302
-     * $att->set( 'ATT_fname', 'Dirk' );
3303
-     * update_option( 'my_option', serialize( $reg ) );
3304
-     * //END REQUEST
3305
-     * //START NEXT REQUEST
3306
-     * $reg = get_option( 'my_option' );
3307
-     * $reg->attendee()->save();
3308
-     * And would need to be replace with:
3309
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3310
-     * $att = $reg->attendee();
3311
-     * $att->set( 'ATT_fname', 'Dirk' );
3312
-     * update_option( 'my_option', serialize( $reg ) );
3313
-     * //END REQUEST
3314
-     * //START NEXT REQUEST
3315
-     * $att = get_option( 'my_option' );
3316
-     * $att->save();
3317
-     *
3318
-     * @return array
3319
-     * @throws ReflectionException
3320
-     * @throws InvalidArgumentException
3321
-     * @throws InvalidInterfaceException
3322
-     * @throws InvalidDataTypeException
3323
-     * @throws EE_Error
3324
-     */
3325
-    public function __sleep()
3326
-    {
3327
-        $model = $this->get_model();
3328
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3329
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3330
-                $classname = 'EE_' . $model->get_this_model_name();
3331
-                if (
3332
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3333
-                    && $this->get_one_from_cache($relation_name)->ID()
3334
-                ) {
3335
-                    $this->clear_cache(
3336
-                        $relation_name,
3337
-                        $this->get_one_from_cache($relation_name)->ID()
3338
-                    );
3339
-                }
3340
-            }
3341
-        }
3342
-        $this->_props_n_values_provided_in_constructor = array();
3343
-        $properties_to_serialize = get_object_vars($this);
3344
-        // don't serialize the model. It's big and that risks recursion
3345
-        unset($properties_to_serialize['_model']);
3346
-        return array_keys($properties_to_serialize);
3347
-    }
3348
-
3349
-
3350
-    /**
3351
-     * restore _props_n_values_provided_in_constructor
3352
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3353
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3354
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3355
-     */
3356
-    public function __wakeup()
3357
-    {
3358
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3359
-    }
3360
-
3361
-
3362
-    /**
3363
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3364
-     * distinct with the clone host instance are also cloned.
3365
-     */
3366
-    public function __clone()
3367
-    {
3368
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3369
-        foreach ($this->_fields as $field => $value) {
3370
-            if ($value instanceof DateTime) {
3371
-                $this->_fields[ $field ] = clone $value;
3372
-            }
3373
-        }
3374
-    }
3268
+				$quantity,
3269
+				EE_INF_IN_DB,
3270
+				$quantity
3271
+			)
3272
+		);
3273
+	}
3274
+
3275
+
3276
+	/**
3277
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3278
+	 * (probably a bad assumption they have made, oh well)
3279
+	 *
3280
+	 * @return string
3281
+	 */
3282
+	public function __toString()
3283
+	{
3284
+		try {
3285
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3286
+		} catch (Exception $e) {
3287
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3288
+			return '';
3289
+		}
3290
+	}
3291
+
3292
+
3293
+	/**
3294
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3295
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3296
+	 * This means if we have made changes to those related model objects, and want to unserialize
3297
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3298
+	 * Instead, those related model objects should be directly serialized and stored.
3299
+	 * Eg, the following won't work:
3300
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
+	 * $att = $reg->attendee();
3302
+	 * $att->set( 'ATT_fname', 'Dirk' );
3303
+	 * update_option( 'my_option', serialize( $reg ) );
3304
+	 * //END REQUEST
3305
+	 * //START NEXT REQUEST
3306
+	 * $reg = get_option( 'my_option' );
3307
+	 * $reg->attendee()->save();
3308
+	 * And would need to be replace with:
3309
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3310
+	 * $att = $reg->attendee();
3311
+	 * $att->set( 'ATT_fname', 'Dirk' );
3312
+	 * update_option( 'my_option', serialize( $reg ) );
3313
+	 * //END REQUEST
3314
+	 * //START NEXT REQUEST
3315
+	 * $att = get_option( 'my_option' );
3316
+	 * $att->save();
3317
+	 *
3318
+	 * @return array
3319
+	 * @throws ReflectionException
3320
+	 * @throws InvalidArgumentException
3321
+	 * @throws InvalidInterfaceException
3322
+	 * @throws InvalidDataTypeException
3323
+	 * @throws EE_Error
3324
+	 */
3325
+	public function __sleep()
3326
+	{
3327
+		$model = $this->get_model();
3328
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3329
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3330
+				$classname = 'EE_' . $model->get_this_model_name();
3331
+				if (
3332
+					$this->get_one_from_cache($relation_name) instanceof $classname
3333
+					&& $this->get_one_from_cache($relation_name)->ID()
3334
+				) {
3335
+					$this->clear_cache(
3336
+						$relation_name,
3337
+						$this->get_one_from_cache($relation_name)->ID()
3338
+					);
3339
+				}
3340
+			}
3341
+		}
3342
+		$this->_props_n_values_provided_in_constructor = array();
3343
+		$properties_to_serialize = get_object_vars($this);
3344
+		// don't serialize the model. It's big and that risks recursion
3345
+		unset($properties_to_serialize['_model']);
3346
+		return array_keys($properties_to_serialize);
3347
+	}
3348
+
3349
+
3350
+	/**
3351
+	 * restore _props_n_values_provided_in_constructor
3352
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3353
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3354
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3355
+	 */
3356
+	public function __wakeup()
3357
+	{
3358
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3359
+	}
3360
+
3361
+
3362
+	/**
3363
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3364
+	 * distinct with the clone host instance are also cloned.
3365
+	 */
3366
+	public function __clone()
3367
+	{
3368
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3369
+		foreach ($this->_fields as $field => $value) {
3370
+			if ($value instanceof DateTime) {
3371
+				$this->_fields[ $field ] = clone $value;
3372
+			}
3373
+		}
3374
+	}
3375 3375
 }
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormAttendeeFactory.php 1 patch
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -16,113 +16,113 @@
 block discarded – undo
16 16
 class RegFormAttendeeFactory
17 17
 {
18 18
 
19
-    /**
20
-     * @var CommandBusInterface
21
-     */
22
-    public $command_bus;
19
+	/**
20
+	 * @var CommandBusInterface
21
+	 */
22
+	public $command_bus;
23 23
 
24
-    /**
25
-     * @var RegistrantData
26
-     */
27
-    private $registrant_data;
24
+	/**
25
+	 * @var RegistrantData
26
+	 */
27
+	private $registrant_data;
28 28
 
29 29
 
30
-    /**
31
-     * RegFormAttendeeFactory constructor.
32
-     *
33
-     * @param CommandBusInterface $command_bus
34
-     * @param RegistrantData      $registrant_data
35
-     */
36
-    public function __construct(CommandBusInterface $command_bus, RegistrantData $registrant_data)
37
-    {
38
-        $this->command_bus     = $command_bus;
39
-        $this->registrant_data = $registrant_data;
40
-    }
30
+	/**
31
+	 * RegFormAttendeeFactory constructor.
32
+	 *
33
+	 * @param CommandBusInterface $command_bus
34
+	 * @param RegistrantData      $registrant_data
35
+	 */
36
+	public function __construct(CommandBusInterface $command_bus, RegistrantData $registrant_data)
37
+	{
38
+		$this->command_bus     = $command_bus;
39
+		$this->registrant_data = $registrant_data;
40
+	}
41 41
 
42 42
 
43
-    /**
44
-     * @param EE_Registration $registration
45
-     * @param string          $reg_url_link
46
-     * @return bool
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public function create(EE_Registration $registration, string $reg_url_link): bool
51
-    {
52
-        // this registration does not require additional attendee information ?
53
-        if (
54
-            $this->registrant_data->copyPrimary()
55
-            && $this->registrant_data->attendeeCount() > 1
56
-            && $this->registrant_data->primaryRegistrantIsValid()
57
-        ) {
58
-            // just copy the primary registrant
59
-            $attendee = $this->registrant_data->primaryRegistrant();
60
-        } else {
61
-            // ensure critical details are set for additional attendees
62
-            // raw form data was already set during call to processRegFormData()
63
-            $this->registrant_data->ensureCriticalRegistrantDataIsSet($reg_url_link);
64
-            // execute create attendee command (which may return an existing attendee)
65
-            $attendee = $this->command_bus->execute(
66
-                new CreateAttendeeCommand(
67
-                    $this->registrant_data->getRegistrantData($reg_url_link),
68
-                    $registration
69
-                )
70
-            );
71
-            // who's #1 ?
72
-            if ($this->registrant_data->currentRegistrantIsPrimary()) {
73
-                $this->registrant_data->setPrimaryRegistrant($attendee);
74
-            }
75
-        }
76
-        // add relation to registration, set attendee ID, and cache attendee
77
-        $this->associateAttendeeWithRegistration($registration, $attendee);
78
-        return $this->isValidAttendee($registration, $reg_url_link);
79
-    }
43
+	/**
44
+	 * @param EE_Registration $registration
45
+	 * @param string          $reg_url_link
46
+	 * @return bool
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public function create(EE_Registration $registration, string $reg_url_link): bool
51
+	{
52
+		// this registration does not require additional attendee information ?
53
+		if (
54
+			$this->registrant_data->copyPrimary()
55
+			&& $this->registrant_data->attendeeCount() > 1
56
+			&& $this->registrant_data->primaryRegistrantIsValid()
57
+		) {
58
+			// just copy the primary registrant
59
+			$attendee = $this->registrant_data->primaryRegistrant();
60
+		} else {
61
+			// ensure critical details are set for additional attendees
62
+			// raw form data was already set during call to processRegFormData()
63
+			$this->registrant_data->ensureCriticalRegistrantDataIsSet($reg_url_link);
64
+			// execute create attendee command (which may return an existing attendee)
65
+			$attendee = $this->command_bus->execute(
66
+				new CreateAttendeeCommand(
67
+					$this->registrant_data->getRegistrantData($reg_url_link),
68
+					$registration
69
+				)
70
+			);
71
+			// who's #1 ?
72
+			if ($this->registrant_data->currentRegistrantIsPrimary()) {
73
+				$this->registrant_data->setPrimaryRegistrant($attendee);
74
+			}
75
+		}
76
+		// add relation to registration, set attendee ID, and cache attendee
77
+		$this->associateAttendeeWithRegistration($registration, $attendee);
78
+		return $this->isValidAttendee($registration, $reg_url_link);
79
+	}
80 80
 
81 81
 
82
-    /**
83
-     * @param EE_Registration $registration
84
-     * @param string          $reg_url_link
85
-     * @return bool
86
-     * @throws EE_Error
87
-     */
88
-    private function isValidAttendee(EE_Registration $registration, string $reg_url_link): bool
89
-    {
90
-        if ($registration->attendee() instanceof EE_Attendee) {
91
-            return true;
92
-        }
93
-        EE_Error::add_error(
94
-            sprintf(
95
-                esc_html_x(
96
-                    'Registration %s has an invalid or missing Attendee object.',
97
-                    'Registration 123-456-789 has an invalid or missing Attendee object.',
98
-                    'event_espresso'
99
-                ),
100
-                $reg_url_link
101
-            ),
102
-            __FILE__,
103
-            __FUNCTION__,
104
-            __LINE__
105
-        );
106
-        return false;
107
-    }
82
+	/**
83
+	 * @param EE_Registration $registration
84
+	 * @param string          $reg_url_link
85
+	 * @return bool
86
+	 * @throws EE_Error
87
+	 */
88
+	private function isValidAttendee(EE_Registration $registration, string $reg_url_link): bool
89
+	{
90
+		if ($registration->attendee() instanceof EE_Attendee) {
91
+			return true;
92
+		}
93
+		EE_Error::add_error(
94
+			sprintf(
95
+				esc_html_x(
96
+					'Registration %s has an invalid or missing Attendee object.',
97
+					'Registration 123-456-789 has an invalid or missing Attendee object.',
98
+					'event_espresso'
99
+				),
100
+				$reg_url_link
101
+			),
102
+			__FILE__,
103
+			__FUNCTION__,
104
+			__LINE__
105
+		);
106
+		return false;
107
+	}
108 108
 
109 109
 
110
-    /**
111
-     * @param EE_Registration $registration
112
-     * @param EE_Attendee     $attendee
113
-     * @return void
114
-     * @throws EE_Error
115
-     * @throws InvalidArgumentException
116
-     * @throws ReflectionException
117
-     * @throws RuntimeException
118
-     * @throws InvalidDataTypeException
119
-     * @throws InvalidInterfaceException
120
-     */
121
-    private function associateAttendeeWithRegistration(EE_Registration $registration, EE_Attendee $attendee)
122
-    {
123
-        // add relation to attendee
124
-        $registration->_add_relation_to($attendee, 'Attendee');
125
-        $registration->set_attendee_id($attendee->ID());
126
-        $registration->update_cache_after_object_save('Attendee', $attendee);
127
-    }
110
+	/**
111
+	 * @param EE_Registration $registration
112
+	 * @param EE_Attendee     $attendee
113
+	 * @return void
114
+	 * @throws EE_Error
115
+	 * @throws InvalidArgumentException
116
+	 * @throws ReflectionException
117
+	 * @throws RuntimeException
118
+	 * @throws InvalidDataTypeException
119
+	 * @throws InvalidInterfaceException
120
+	 */
121
+	private function associateAttendeeWithRegistration(EE_Registration $registration, EE_Attendee $attendee)
122
+	{
123
+		// add relation to attendee
124
+		$registration->_add_relation_to($attendee, 'Attendee');
125
+		$registration->set_attendee_id($attendee->ID());
126
+		$registration->update_cache_after_object_save('Attendee', $attendee);
127
+	}
128 128
 }
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormDependencyHandler.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -7,61 +7,61 @@
 block discarded – undo
7 7
 
8 8
 class RegFormDependencyHandler extends DependencyHandler
9 9
 {
10
-    /**
11
-     * @return void
12
-     */
13
-    public function registerDependencies()
14
-    {
15
-        $reg_form_dependencies = [
16
-            'EventEspresso\core\domain\services\registration\form\v1\RegForm'                => [
17
-                null,
18
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
19
-            ],
20
-            'EventEspresso\core\domain\services\registration\form\v1\RegistrantForm'         => [
21
-                null,
22
-                null,
23
-                null,
24
-                null,
25
-                'EEM_Event_Question_Group' => EE_Dependency_Map::load_from_cache,
26
-            ],
27
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionFactory' => [
28
-                null,
29
-                'EEM_Answer' => EE_Dependency_Map::load_from_cache,
30
-            ],
31
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionGroup'   => [
32
-                null,
33
-                null,
34
-                null,
35
-                'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionFactory' => EE_Dependency_Map::load_from_cache,
36
-            ],
37
-            'EventEspresso\core\domain\services\registration\form\v1\CountryOptions'         => [
38
-                null,
39
-                'EEM_Answer'  => EE_Dependency_Map::load_from_cache,
40
-                'EEM_Country' => EE_Dependency_Map::load_from_cache,
41
-            ],
42
-            'EventEspresso\core\domain\services\registration\form\v1\StateOptions'           => [
43
-                null,
44
-                'EEM_State' => EE_Dependency_Map::load_from_cache,
45
-            ],
46
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormHandler'         => [
47
-                null,
48
-                'EventEspresso\core\domain\services\registration\form\v1\RegistrantData'         => EE_Dependency_Map::load_from_cache,
49
-                'EventEspresso\core\domain\services\registration\form\v1\RegFormAttendeeFactory' => EE_Dependency_Map::load_from_cache,
50
-                'EE_Registration_Processor'                                                      => EE_Dependency_Map::load_from_cache,
51
-            ],
52
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormInputHandler'    => [
53
-                null,
54
-                null,
55
-                'EEM_Attendee'                                                           => EE_Dependency_Map::load_from_cache,
56
-                'EventEspresso\core\domain\services\registration\form\v1\RegistrantData' => EE_Dependency_Map::load_from_cache,
57
-            ],
58
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormAttendeeFactory' => [
59
-                'EventEspresso\core\services\commands\CommandBus'                        => EE_Dependency_Map::load_from_cache,
60
-                'EventEspresso\core\domain\services\registration\form\v1\RegistrantData' => EE_Dependency_Map::load_from_cache,
61
-            ],
62
-        ];
63
-        foreach ($reg_form_dependencies as $class => $dependencies) {
64
-            $this->dependency_map->registerDependencies($class, $dependencies);
65
-        }
66
-    }
10
+	/**
11
+	 * @return void
12
+	 */
13
+	public function registerDependencies()
14
+	{
15
+		$reg_form_dependencies = [
16
+			'EventEspresso\core\domain\services\registration\form\v1\RegForm'                => [
17
+				null,
18
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
19
+			],
20
+			'EventEspresso\core\domain\services\registration\form\v1\RegistrantForm'         => [
21
+				null,
22
+				null,
23
+				null,
24
+				null,
25
+				'EEM_Event_Question_Group' => EE_Dependency_Map::load_from_cache,
26
+			],
27
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionFactory' => [
28
+				null,
29
+				'EEM_Answer' => EE_Dependency_Map::load_from_cache,
30
+			],
31
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionGroup'   => [
32
+				null,
33
+				null,
34
+				null,
35
+				'EventEspresso\core\domain\services\registration\form\v1\RegFormQuestionFactory' => EE_Dependency_Map::load_from_cache,
36
+			],
37
+			'EventEspresso\core\domain\services\registration\form\v1\CountryOptions'         => [
38
+				null,
39
+				'EEM_Answer'  => EE_Dependency_Map::load_from_cache,
40
+				'EEM_Country' => EE_Dependency_Map::load_from_cache,
41
+			],
42
+			'EventEspresso\core\domain\services\registration\form\v1\StateOptions'           => [
43
+				null,
44
+				'EEM_State' => EE_Dependency_Map::load_from_cache,
45
+			],
46
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormHandler'         => [
47
+				null,
48
+				'EventEspresso\core\domain\services\registration\form\v1\RegistrantData'         => EE_Dependency_Map::load_from_cache,
49
+				'EventEspresso\core\domain\services\registration\form\v1\RegFormAttendeeFactory' => EE_Dependency_Map::load_from_cache,
50
+				'EE_Registration_Processor'                                                      => EE_Dependency_Map::load_from_cache,
51
+			],
52
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormInputHandler'    => [
53
+				null,
54
+				null,
55
+				'EEM_Attendee'                                                           => EE_Dependency_Map::load_from_cache,
56
+				'EventEspresso\core\domain\services\registration\form\v1\RegistrantData' => EE_Dependency_Map::load_from_cache,
57
+			],
58
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormAttendeeFactory' => [
59
+				'EventEspresso\core\services\commands\CommandBus'                        => EE_Dependency_Map::load_from_cache,
60
+				'EventEspresso\core\domain\services\registration\form\v1\RegistrantData' => EE_Dependency_Map::load_from_cache,
61
+			],
62
+		];
63
+		foreach ($reg_form_dependencies as $class => $dependencies) {
64
+			$this->dependency_map->registerDependencies($class, $dependencies);
65
+		}
66
+	}
67 67
 }
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormQuestionFactory.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             $registration,
57 57
             $question->system_ID()
58 58
         );
59
-        $answer       = $answer_value === null
59
+        $answer = $answer_value === null
60 60
             ? $this->answer_model->get_one(
61 61
                 [['QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()]]
62 62
             )
@@ -75,14 +75,14 @@  discard block
 block discarded – undo
75 75
         }
76 76
         // verify instance
77 77
         if ($answer instanceof EE_Answer) {
78
-            if (! empty($answer_value)) {
78
+            if ( ! empty($answer_value)) {
79 79
                 $answer->set('ANS_value', $answer_value);
80 80
             }
81 81
             $answer->cache('Question', $question);
82 82
             // remember system ID had a bug where sometimes it could be null
83 83
             $answer_cache_id = $question->is_system_question()
84
-                ? $question->system_ID() . '-' . $registration->reg_url_link()
85
-                : $question->ID() . '-' . $registration->reg_url_link();
84
+                ? $question->system_ID().'-'.$registration->reg_url_link()
85
+                : $question->ID().'-'.$registration->reg_url_link();
86 86
             $registration->cache('Answer', $answer, $answer_cache_id);
87 87
         }
88 88
         return $this->generateQuestionInput($registration, $question, $answer);
@@ -105,23 +105,23 @@  discard block
 block discarded – undo
105 105
         EE_Question $question,
106 106
         $answer
107 107
     ): EE_Form_Input_Base {
108
-        $identifier                              = $question->is_system_question()
108
+        $identifier = $question->is_system_question()
109 109
             ? $question->system_ID()
110 110
             : $question->ID();
111 111
         $callback = $this->addRequiredQuestion;
112 112
         $callback($identifier, $question->required());
113
-        $input_constructor_args                  = [
114
-            'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
115
-            'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
116
-            'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
117
-            'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
113
+        $input_constructor_args = [
114
+            'html_name'        => 'ee_reg_qstn['.$registration->ID().']['.$identifier.']',
115
+            'html_id'          => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
116
+            'html_class'       => 'ee-reg-qstn ee-reg-qstn-'.$identifier,
117
+            'html_label_id'    => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
118 118
             'html_label_class' => 'ee-reg-qstn',
119 119
         ];
120 120
         $input_constructor_args['html_label_id'] .= '-lbl';
121 121
         if ($answer instanceof EE_Answer && $answer->ID()) {
122
-            $input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
123
-            $input_constructor_args['html_id']       .= '-' . $answer->ID();
124
-            $input_constructor_args['html_label_id'] .= '-' . $answer->ID();
122
+            $input_constructor_args['html_name']     .= '['.$answer->ID().']';
123
+            $input_constructor_args['html_id']       .= '-'.$answer->ID();
124
+            $input_constructor_args['html_label_id'] .= '-'.$answer->ID();
125 125
         }
126 126
         return $question->generate_form_input(
127 127
             $registration,
Please login to merge, or discard this patch.
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -16,118 +16,118 @@
 block discarded – undo
16 16
 class RegFormQuestionFactory
17 17
 {
18 18
 
19
-    /**
20
-     * @var callable
21
-     */
22
-    protected $addRequiredQuestion;
19
+	/**
20
+	 * @var callable
21
+	 */
22
+	protected $addRequiredQuestion;
23 23
 
24
-    /**
25
-     * @var EEM_Answer
26
-     */
27
-    public $answer_model;
24
+	/**
25
+	 * @var EEM_Answer
26
+	 */
27
+	public $answer_model;
28 28
 
29 29
 
30
-    /**
31
-     * @param callable   $addRequiredQuestion
32
-     * @param EEM_Answer $answer_model
33
-     */
34
-    public function __construct(callable $addRequiredQuestion, EEM_Answer $answer_model)
35
-    {
36
-        $this->addRequiredQuestion = $addRequiredQuestion;
37
-        $this->answer_model = $answer_model;
38
-    }
30
+	/**
31
+	 * @param callable   $addRequiredQuestion
32
+	 * @param EEM_Answer $answer_model
33
+	 */
34
+	public function __construct(callable $addRequiredQuestion, EEM_Answer $answer_model)
35
+	{
36
+		$this->addRequiredQuestion = $addRequiredQuestion;
37
+		$this->answer_model = $answer_model;
38
+	}
39 39
 
40 40
 
41
-    /**
42
-     * @param EE_Registration $registration
43
-     * @param EE_Question     $question
44
-     * @return EE_Form_Input_Base
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     * @throws InvalidInterfaceException
49
-     * @throws ReflectionException
50
-     */
51
-    public function create(
52
-        EE_Registration $registration,
53
-        EE_Question $question
54
-    ): EE_Form_Input_Base {
55
-        // if this question was for an attendee detail, then check for that answer
56
-        $answer_value = $this->answer_model->get_attendee_property_answer_value(
57
-            $registration,
58
-            $question->system_ID()
59
-        );
60
-        $answer       = $answer_value === null
61
-            ? $this->answer_model->get_one(
62
-                [['QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()]]
63
-            )
64
-            : null;
65
-        // if NOT returning to edit an existing registration
66
-        // OR if this question is for an attendee property
67
-        // OR we still don't have an EE_Answer object
68
-        if ($answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link()) {
69
-            // create an EE_Answer object for storing everything in
70
-            $answer = EE_Answer::new_instance(
71
-                [
72
-                    'QST_ID' => $question->ID(),
73
-                    'REG_ID' => $registration->ID(),
74
-                ]
75
-            );
76
-        }
77
-        // verify instance
78
-        if ($answer instanceof EE_Answer) {
79
-            if (! empty($answer_value)) {
80
-                $answer->set('ANS_value', $answer_value);
81
-            }
82
-            $answer->cache('Question', $question);
83
-            // remember system ID had a bug where sometimes it could be null
84
-            $answer_cache_id = $question->is_system_question()
85
-                ? $question->system_ID() . '-' . $registration->reg_url_link()
86
-                : $question->ID() . '-' . $registration->reg_url_link();
87
-            $registration->cache('Answer', $answer, $answer_cache_id);
88
-        }
89
-        return $this->generateQuestionInput($registration, $question, $answer);
90
-    }
41
+	/**
42
+	 * @param EE_Registration $registration
43
+	 * @param EE_Question     $question
44
+	 * @return EE_Form_Input_Base
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws ReflectionException
50
+	 */
51
+	public function create(
52
+		EE_Registration $registration,
53
+		EE_Question $question
54
+	): EE_Form_Input_Base {
55
+		// if this question was for an attendee detail, then check for that answer
56
+		$answer_value = $this->answer_model->get_attendee_property_answer_value(
57
+			$registration,
58
+			$question->system_ID()
59
+		);
60
+		$answer       = $answer_value === null
61
+			? $this->answer_model->get_one(
62
+				[['QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()]]
63
+			)
64
+			: null;
65
+		// if NOT returning to edit an existing registration
66
+		// OR if this question is for an attendee property
67
+		// OR we still don't have an EE_Answer object
68
+		if ($answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link()) {
69
+			// create an EE_Answer object for storing everything in
70
+			$answer = EE_Answer::new_instance(
71
+				[
72
+					'QST_ID' => $question->ID(),
73
+					'REG_ID' => $registration->ID(),
74
+				]
75
+			);
76
+		}
77
+		// verify instance
78
+		if ($answer instanceof EE_Answer) {
79
+			if (! empty($answer_value)) {
80
+				$answer->set('ANS_value', $answer_value);
81
+			}
82
+			$answer->cache('Question', $question);
83
+			// remember system ID had a bug where sometimes it could be null
84
+			$answer_cache_id = $question->is_system_question()
85
+				? $question->system_ID() . '-' . $registration->reg_url_link()
86
+				: $question->ID() . '-' . $registration->reg_url_link();
87
+			$registration->cache('Answer', $answer, $answer_cache_id);
88
+		}
89
+		return $this->generateQuestionInput($registration, $question, $answer);
90
+	}
91 91
 
92 92
 
93
-    /**
94
-     * @param EE_Registration $registration
95
-     * @param EE_Question     $question
96
-     * @param                 $answer
97
-     * @return EE_Form_Input_Base
98
-     * @throws EE_Error
99
-     * @throws InvalidArgumentException
100
-     * @throws ReflectionException
101
-     * @throws InvalidDataTypeException
102
-     * @throws InvalidInterfaceException
103
-     */
104
-    private function generateQuestionInput(
105
-        EE_Registration $registration,
106
-        EE_Question $question,
107
-        $answer
108
-    ): EE_Form_Input_Base {
109
-        $identifier                              = $question->is_system_question()
110
-            ? $question->system_ID()
111
-            : $question->ID();
112
-        $callback = $this->addRequiredQuestion;
113
-        $callback($identifier, $question->required());
114
-        $input_constructor_args                  = [
115
-            'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
116
-            'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
117
-            'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
118
-            'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
119
-            'html_label_class' => 'ee-reg-qstn',
120
-        ];
121
-        $input_constructor_args['html_label_id'] .= '-lbl';
122
-        if ($answer instanceof EE_Answer && $answer->ID()) {
123
-            $input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
124
-            $input_constructor_args['html_id']       .= '-' . $answer->ID();
125
-            $input_constructor_args['html_label_id'] .= '-' . $answer->ID();
126
-        }
127
-        return $question->generate_form_input(
128
-            $registration,
129
-            $answer,
130
-            $input_constructor_args
131
-        );
132
-    }
93
+	/**
94
+	 * @param EE_Registration $registration
95
+	 * @param EE_Question     $question
96
+	 * @param                 $answer
97
+	 * @return EE_Form_Input_Base
98
+	 * @throws EE_Error
99
+	 * @throws InvalidArgumentException
100
+	 * @throws ReflectionException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws InvalidInterfaceException
103
+	 */
104
+	private function generateQuestionInput(
105
+		EE_Registration $registration,
106
+		EE_Question $question,
107
+		$answer
108
+	): EE_Form_Input_Base {
109
+		$identifier                              = $question->is_system_question()
110
+			? $question->system_ID()
111
+			: $question->ID();
112
+		$callback = $this->addRequiredQuestion;
113
+		$callback($identifier, $question->required());
114
+		$input_constructor_args                  = [
115
+			'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
116
+			'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
117
+			'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
118
+			'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
119
+			'html_label_class' => 'ee-reg-qstn',
120
+		];
121
+		$input_constructor_args['html_label_id'] .= '-lbl';
122
+		if ($answer instanceof EE_Answer && $answer->ID()) {
123
+			$input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
124
+			$input_constructor_args['html_id']       .= '-' . $answer->ID();
125
+			$input_constructor_args['html_label_id'] .= '-' . $answer->ID();
126
+		}
127
+		return $question->generate_form_input(
128
+			$registration,
129
+			$answer,
130
+			$input_constructor_args
131
+		);
132
+	}
133 133
 }
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegistrantForm.php 2 patches
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -17,192 +17,192 @@
 block discarded – undo
17 17
 class RegistrantForm extends EE_Form_Section_Proper
18 18
 {
19 19
 
20
-    /**
21
-     * @var EEM_Event_Question_Group
22
-     */
23
-    public $event_question_group_model;
24
-
25
-    /**
26
-     * @var bool
27
-     */
28
-    private $has_questions = false;
29
-
30
-
31
-    /**
32
-     * RegistrantForm constructor.
33
-     *
34
-     * @param EE_Registration          $registration
35
-     * @param bool                     $admin_request
36
-     * @param bool                     $copy_attendee_info
37
-     * @param callable                 $enablePrintCopyInfo
38
-     * @param EEM_Event_Question_Group $event_question_group_model
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public function __construct(
43
-        EE_Registration $registration,
44
-        bool $admin_request,
45
-        bool $copy_attendee_info,
46
-        callable $enablePrintCopyInfo,
47
-        EEM_Event_Question_Group $event_question_group_model
48
-    ) {
49
-        $this->event_question_group_model = $event_question_group_model;
50
-        parent::__construct(
51
-            $this->generateFormArgs($registration, $admin_request, $copy_attendee_info, $enablePrintCopyInfo)
52
-        );
53
-    }
54
-
55
-
56
-    /**
57
-     * @return bool
58
-     */
59
-    public function hasQuestions(): bool
60
-    {
61
-        return $this->has_questions;
62
-    }
63
-
64
-
65
-    /**
66
-     * @param EE_Registration $registration
67
-     * @param bool            $admin_request
68
-     * @param bool            $copy_attendee_info
69
-     * @param callable        $enablePrintCopyInfo
70
-     * @return array
71
-     * @throws EE_Error
72
-     * @throws ReflectionException
73
-     */
74
-    private function generateFormArgs(
75
-        EE_Registration $registration,
76
-        bool $admin_request,
77
-        bool $copy_attendee_info,
78
-        callable $enablePrintCopyInfo
79
-    ): array {
80
-        static $attendee_nmbr = 1;
81
-        $form_args = [];
82
-        // verify that registration has valid event
83
-        if ($registration->event() instanceof EE_Event) {
84
-            $field_name      = 'Event_Question_Group.' . $this->event_question_group_model->fieldNameForContext(
85
-                $registration->is_primary_registrant()
86
-            );
87
-            $question_groups = $registration->event()->question_groups(
88
-                apply_filters(
89
-                    // @codingStandardsIgnoreStart
90
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___registrations_reg_form__question_groups_query_parameters',
91
-                    // @codingStandardsIgnoreEnd
92
-                    [
93
-                        [
94
-                            'Event.EVT_ID' => $registration->event()->ID(),
95
-                            $field_name    => true,
96
-                        ],
97
-                        'order_by' => ['QSG_order' => 'ASC'],
98
-                    ],
99
-                    $registration,
100
-                    $this
101
-                )
102
-            );
103
-            if ($question_groups) {
104
-                // array of params to pass to parent constructor
105
-                $form_args = [
106
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
107
-                    'html_class'      => 'ee-reg-form-attendee-dv',
108
-                    'html_style'      => $admin_request
109
-                        ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
110
-                        : '',
111
-                    'subsections'     => [],
112
-                    'layout_strategy' => new EE_Fieldset_Section_Layout(
113
-                        [
114
-                            'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
115
-                            'legend_text'  => sprintf(
116
-                                esc_html_x(
117
-                                    'Attendee %d',
118
-                                    'Attendee 123',
119
-                                    'event_espresso'
120
-                                ),
121
-                                $attendee_nmbr
122
-                            ),
123
-                        ]
124
-                    ),
125
-                ];
126
-                foreach ($question_groups as $question_group) {
127
-                    if ($question_group instanceof EE_Question_Group) {
128
-                        $question_group_reg_form = LoaderFactory::getNew(
129
-                            RegFormQuestionGroup::class,
130
-                            [$registration, $question_group, $admin_request]
131
-                        );
132
-                        $form_args['subsections'][ $question_group->identifier() ] = apply_filters(
133
-                            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
134
-                            $question_group_reg_form,
135
-                            $registration,
136
-                            $question_group,
137
-                            $this
138
-                        );
139
-                    }
140
-                }
141
-                // add hidden input
142
-                $form_args['subsections']['additional_attendee_reg_info'] = $this->additionalAttendeeRegInfoInput(
143
-                    $registration
144
-                );
145
-
146
-                // If we have question groups for additional attendees, then display the copy options
147
-                $printCopyInfo = apply_filters(
148
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___registrations_reg_form___printCopyInfo',
149
-                    $attendee_nmbr > 1 && $copy_attendee_info,
150
-                    $attendee_nmbr
151
-                );
152
-                if ($printCopyInfo) {
153
-                    $enablePrintCopyInfo();
154
-                }
155
-
156
-
157
-                if ($registration->is_primary_registrant()) {
158
-                    // generate hidden input
159
-                    $form_args['subsections']['primary_registrant'] = $this->additionalPrimaryRegistrantInputs(
160
-                        $registration
161
-                    );
162
-                }
163
-            }
164
-        }
165
-        $attendee_nmbr++;
166
-
167
-        // Increment the reg forms number if form is valid.
168
-        if (! empty($form_args)) {
169
-            $this->has_questions = true;
170
-        }
171
-
172
-        return $form_args;
173
-    }
174
-
175
-
176
-    /**
177
-     * @param EE_Registration $registration
178
-     * @return EE_Form_Input_Base
179
-     * @throws EE_Error
180
-     */
181
-    private function additionalAttendeeRegInfoInput(EE_Registration $registration)
182
-    {
183
-        // generate hidden input
184
-        return new EE_Hidden_Input(
185
-            [
186
-                'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
187
-                'default' => true,
188
-            ]
189
-        );
190
-    }
191
-
192
-
193
-    /**
194
-     * @param EE_Registration $registration
195
-     * @return    EE_Form_Input_Base
196
-     * @throws EE_Error
197
-     */
198
-    private function additionalPrimaryRegistrantInputs(EE_Registration $registration)
199
-    {
200
-        // generate hidden input
201
-        return new EE_Hidden_Input(
202
-            [
203
-                'html_id' => 'primary_registrant',
204
-                'default' => $registration->reg_url_link(),
205
-            ]
206
-        );
207
-    }
20
+	/**
21
+	 * @var EEM_Event_Question_Group
22
+	 */
23
+	public $event_question_group_model;
24
+
25
+	/**
26
+	 * @var bool
27
+	 */
28
+	private $has_questions = false;
29
+
30
+
31
+	/**
32
+	 * RegistrantForm constructor.
33
+	 *
34
+	 * @param EE_Registration          $registration
35
+	 * @param bool                     $admin_request
36
+	 * @param bool                     $copy_attendee_info
37
+	 * @param callable                 $enablePrintCopyInfo
38
+	 * @param EEM_Event_Question_Group $event_question_group_model
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function __construct(
43
+		EE_Registration $registration,
44
+		bool $admin_request,
45
+		bool $copy_attendee_info,
46
+		callable $enablePrintCopyInfo,
47
+		EEM_Event_Question_Group $event_question_group_model
48
+	) {
49
+		$this->event_question_group_model = $event_question_group_model;
50
+		parent::__construct(
51
+			$this->generateFormArgs($registration, $admin_request, $copy_attendee_info, $enablePrintCopyInfo)
52
+		);
53
+	}
54
+
55
+
56
+	/**
57
+	 * @return bool
58
+	 */
59
+	public function hasQuestions(): bool
60
+	{
61
+		return $this->has_questions;
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param EE_Registration $registration
67
+	 * @param bool            $admin_request
68
+	 * @param bool            $copy_attendee_info
69
+	 * @param callable        $enablePrintCopyInfo
70
+	 * @return array
71
+	 * @throws EE_Error
72
+	 * @throws ReflectionException
73
+	 */
74
+	private function generateFormArgs(
75
+		EE_Registration $registration,
76
+		bool $admin_request,
77
+		bool $copy_attendee_info,
78
+		callable $enablePrintCopyInfo
79
+	): array {
80
+		static $attendee_nmbr = 1;
81
+		$form_args = [];
82
+		// verify that registration has valid event
83
+		if ($registration->event() instanceof EE_Event) {
84
+			$field_name      = 'Event_Question_Group.' . $this->event_question_group_model->fieldNameForContext(
85
+				$registration->is_primary_registrant()
86
+			);
87
+			$question_groups = $registration->event()->question_groups(
88
+				apply_filters(
89
+					// @codingStandardsIgnoreStart
90
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___registrations_reg_form__question_groups_query_parameters',
91
+					// @codingStandardsIgnoreEnd
92
+					[
93
+						[
94
+							'Event.EVT_ID' => $registration->event()->ID(),
95
+							$field_name    => true,
96
+						],
97
+						'order_by' => ['QSG_order' => 'ASC'],
98
+					],
99
+					$registration,
100
+					$this
101
+				)
102
+			);
103
+			if ($question_groups) {
104
+				// array of params to pass to parent constructor
105
+				$form_args = [
106
+					'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
107
+					'html_class'      => 'ee-reg-form-attendee-dv',
108
+					'html_style'      => $admin_request
109
+						? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
110
+						: '',
111
+					'subsections'     => [],
112
+					'layout_strategy' => new EE_Fieldset_Section_Layout(
113
+						[
114
+							'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
115
+							'legend_text'  => sprintf(
116
+								esc_html_x(
117
+									'Attendee %d',
118
+									'Attendee 123',
119
+									'event_espresso'
120
+								),
121
+								$attendee_nmbr
122
+							),
123
+						]
124
+					),
125
+				];
126
+				foreach ($question_groups as $question_group) {
127
+					if ($question_group instanceof EE_Question_Group) {
128
+						$question_group_reg_form = LoaderFactory::getNew(
129
+							RegFormQuestionGroup::class,
130
+							[$registration, $question_group, $admin_request]
131
+						);
132
+						$form_args['subsections'][ $question_group->identifier() ] = apply_filters(
133
+							'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
134
+							$question_group_reg_form,
135
+							$registration,
136
+							$question_group,
137
+							$this
138
+						);
139
+					}
140
+				}
141
+				// add hidden input
142
+				$form_args['subsections']['additional_attendee_reg_info'] = $this->additionalAttendeeRegInfoInput(
143
+					$registration
144
+				);
145
+
146
+				// If we have question groups for additional attendees, then display the copy options
147
+				$printCopyInfo = apply_filters(
148
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___registrations_reg_form___printCopyInfo',
149
+					$attendee_nmbr > 1 && $copy_attendee_info,
150
+					$attendee_nmbr
151
+				);
152
+				if ($printCopyInfo) {
153
+					$enablePrintCopyInfo();
154
+				}
155
+
156
+
157
+				if ($registration->is_primary_registrant()) {
158
+					// generate hidden input
159
+					$form_args['subsections']['primary_registrant'] = $this->additionalPrimaryRegistrantInputs(
160
+						$registration
161
+					);
162
+				}
163
+			}
164
+		}
165
+		$attendee_nmbr++;
166
+
167
+		// Increment the reg forms number if form is valid.
168
+		if (! empty($form_args)) {
169
+			$this->has_questions = true;
170
+		}
171
+
172
+		return $form_args;
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param EE_Registration $registration
178
+	 * @return EE_Form_Input_Base
179
+	 * @throws EE_Error
180
+	 */
181
+	private function additionalAttendeeRegInfoInput(EE_Registration $registration)
182
+	{
183
+		// generate hidden input
184
+		return new EE_Hidden_Input(
185
+			[
186
+				'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
187
+				'default' => true,
188
+			]
189
+		);
190
+	}
191
+
192
+
193
+	/**
194
+	 * @param EE_Registration $registration
195
+	 * @return    EE_Form_Input_Base
196
+	 * @throws EE_Error
197
+	 */
198
+	private function additionalPrimaryRegistrantInputs(EE_Registration $registration)
199
+	{
200
+		// generate hidden input
201
+		return new EE_Hidden_Input(
202
+			[
203
+				'html_id' => 'primary_registrant',
204
+				'default' => $registration->reg_url_link(),
205
+			]
206
+		);
207
+	}
208 208
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
         $form_args = [];
82 82
         // verify that registration has valid event
83 83
         if ($registration->event() instanceof EE_Event) {
84
-            $field_name      = 'Event_Question_Group.' . $this->event_question_group_model->fieldNameForContext(
84
+            $field_name      = 'Event_Question_Group.'.$this->event_question_group_model->fieldNameForContext(
85 85
                 $registration->is_primary_registrant()
86 86
             );
87 87
             $question_groups = $registration->event()->question_groups(
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
             if ($question_groups) {
104 104
                 // array of params to pass to parent constructor
105 105
                 $form_args = [
106
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
106
+                    'html_id'         => 'ee-registration-'.$registration->reg_url_link(),
107 107
                     'html_class'      => 'ee-reg-form-attendee-dv',
108 108
                     'html_style'      => $admin_request
109 109
                         ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
                             RegFormQuestionGroup::class,
130 130
                             [$registration, $question_group, $admin_request]
131 131
                         );
132
-                        $form_args['subsections'][ $question_group->identifier() ] = apply_filters(
132
+                        $form_args['subsections'][$question_group->identifier()] = apply_filters(
133 133
                             'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
134 134
                             $question_group_reg_form,
135 135
                             $registration,
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
         $attendee_nmbr++;
166 166
 
167 167
         // Increment the reg forms number if form is valid.
168
-        if (! empty($form_args)) {
168
+        if ( ! empty($form_args)) {
169 169
             $this->has_questions = true;
170 170
         }
171 171
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
         // generate hidden input
184 184
         return new EE_Hidden_Input(
185 185
             [
186
-                'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
186
+                'html_id' => 'additional-attendee-reg-info-'.$registration->reg_url_link(),
187 187
                 'default' => true,
188 188
             ]
189 189
         );
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormInputHandler.php 2 patches
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -14,223 +14,223 @@
 block discarded – undo
14 14
 class RegFormInputHandler
15 15
 {
16 16
 
17
-    /**
18
-     * @var EEM_Attendee
19
-     */
20
-    private $attendee_model;
21
-
22
-    /**
23
-     * @var string
24
-     */
25
-    private $checkout_reg_url_link;
26
-
27
-    /**
28
-     * @var RegistrantData
29
-     */
30
-    private $registrant_data;
31
-
32
-    /**
33
-     * @var array
34
-     */
35
-    private $required_questions;
36
-
37
-
38
-    /**
39
-     * RegFormHandler constructor.
40
-     */
41
-    public function __construct(
42
-        string $checkout_reg_url_link,
43
-        array $required_questions,
44
-        EEM_Attendee $attendee_model,
45
-        RegistrantData $registrant_data
46
-    ) {
47
-        $this->attendee_model        = $attendee_model;
48
-        $this->checkout_reg_url_link = $checkout_reg_url_link;
49
-        $this->registrant_data       = $registrant_data;
50
-        $this->required_questions    = $required_questions;
51
-    }
52
-
53
-
54
-    /**
55
-     * @param EE_Registration  $registration
56
-     * @param string           $reg_url_link
57
-     * @param int|string       $form_input
58
-     * @param float|int|string $input_value
59
-     * @return bool
60
-     * @throws EE_Error
61
-     * @throws ReflectionException
62
-     */
63
-    public function processFormInput(
64
-        EE_Registration $registration,
65
-        string $reg_url_link,
66
-        $form_input,
67
-        $input_value
68
-    ): bool {
69
-        // check for critical inputs
70
-        if (! $this->verifyCriticalAttendeeDetailsAreSetAndValidateEmail($form_input, $input_value)) {
71
-            return false;
72
-        }
73
-        $input_value = $this->registrant_data->saveOrCopyPrimaryRegistrantData(
74
-            $reg_url_link,
75
-            $form_input,
76
-            $input_value
77
-        );
78
-        if (! $this->saveRegistrationFormInput($registration, $reg_url_link, $form_input, $input_value)) {
79
-            EE_Error::add_error(
80
-                sprintf(
81
-                    esc_html_x(
82
-                        'Unable to save registration form data for the form input: "%1$s" with the submitted value: "%2$s"',
83
-                        'Unable to save registration form data for the form input: "form input name" with the submitted value: "form input value"',
84
-                        'event_espresso'
85
-                    ),
86
-                    $form_input,
87
-                    $input_value
88
-                ),
89
-                __FILE__,
90
-                __FUNCTION__,
91
-                __LINE__
92
-            );
93
-            return false;
94
-        }
95
-        return true;
96
-    }
97
-
98
-
99
-    /**
100
-     * @param EE_Registration  $registration
101
-     * @param string           $reg_url_link
102
-     * @param int|string       $form_input
103
-     * @param float|int|string $input_value
104
-     * @return bool
105
-     * @throws EE_Error
106
-     * @throws InvalidArgumentException
107
-     * @throws InvalidDataTypeException
108
-     * @throws InvalidInterfaceException
109
-     * @throws ReflectionException
110
-     */
111
-    private function saveRegistrationFormInput(
112
-        EE_Registration $registration,
113
-        string $reg_url_link,
114
-        $form_input = '',
115
-        $input_value = ''
116
-    ): bool {
117
-        // If email_confirm is sent it's not saved
118
-        if ((string) $form_input === 'email_confirm') {
119
-            return true;
120
-        }
121
-        // allow for plugins to hook in and do their own processing of the form input.
122
-        // For plugins to bypass normal processing here, they just need to return a truthy value.
123
-        if (
124
-            apply_filters(
125
-                'FHEE__EE_SPCO_Reg_Step_Attendee_Information___save_registration_form_input',
126
-                false,
127
-                $registration,
128
-                $form_input,
129
-                $input_value,
130
-                $this
131
-            )
132
-        ) {
133
-            return true;
134
-        }
135
-        /*
17
+	/**
18
+	 * @var EEM_Attendee
19
+	 */
20
+	private $attendee_model;
21
+
22
+	/**
23
+	 * @var string
24
+	 */
25
+	private $checkout_reg_url_link;
26
+
27
+	/**
28
+	 * @var RegistrantData
29
+	 */
30
+	private $registrant_data;
31
+
32
+	/**
33
+	 * @var array
34
+	 */
35
+	private $required_questions;
36
+
37
+
38
+	/**
39
+	 * RegFormHandler constructor.
40
+	 */
41
+	public function __construct(
42
+		string $checkout_reg_url_link,
43
+		array $required_questions,
44
+		EEM_Attendee $attendee_model,
45
+		RegistrantData $registrant_data
46
+	) {
47
+		$this->attendee_model        = $attendee_model;
48
+		$this->checkout_reg_url_link = $checkout_reg_url_link;
49
+		$this->registrant_data       = $registrant_data;
50
+		$this->required_questions    = $required_questions;
51
+	}
52
+
53
+
54
+	/**
55
+	 * @param EE_Registration  $registration
56
+	 * @param string           $reg_url_link
57
+	 * @param int|string       $form_input
58
+	 * @param float|int|string $input_value
59
+	 * @return bool
60
+	 * @throws EE_Error
61
+	 * @throws ReflectionException
62
+	 */
63
+	public function processFormInput(
64
+		EE_Registration $registration,
65
+		string $reg_url_link,
66
+		$form_input,
67
+		$input_value
68
+	): bool {
69
+		// check for critical inputs
70
+		if (! $this->verifyCriticalAttendeeDetailsAreSetAndValidateEmail($form_input, $input_value)) {
71
+			return false;
72
+		}
73
+		$input_value = $this->registrant_data->saveOrCopyPrimaryRegistrantData(
74
+			$reg_url_link,
75
+			$form_input,
76
+			$input_value
77
+		);
78
+		if (! $this->saveRegistrationFormInput($registration, $reg_url_link, $form_input, $input_value)) {
79
+			EE_Error::add_error(
80
+				sprintf(
81
+					esc_html_x(
82
+						'Unable to save registration form data for the form input: "%1$s" with the submitted value: "%2$s"',
83
+						'Unable to save registration form data for the form input: "form input name" with the submitted value: "form input value"',
84
+						'event_espresso'
85
+					),
86
+					$form_input,
87
+					$input_value
88
+				),
89
+				__FILE__,
90
+				__FUNCTION__,
91
+				__LINE__
92
+			);
93
+			return false;
94
+		}
95
+		return true;
96
+	}
97
+
98
+
99
+	/**
100
+	 * @param EE_Registration  $registration
101
+	 * @param string           $reg_url_link
102
+	 * @param int|string       $form_input
103
+	 * @param float|int|string $input_value
104
+	 * @return bool
105
+	 * @throws EE_Error
106
+	 * @throws InvalidArgumentException
107
+	 * @throws InvalidDataTypeException
108
+	 * @throws InvalidInterfaceException
109
+	 * @throws ReflectionException
110
+	 */
111
+	private function saveRegistrationFormInput(
112
+		EE_Registration $registration,
113
+		string $reg_url_link,
114
+		$form_input = '',
115
+		$input_value = ''
116
+	): bool {
117
+		// If email_confirm is sent it's not saved
118
+		if ((string) $form_input === 'email_confirm') {
119
+			return true;
120
+		}
121
+		// allow for plugins to hook in and do their own processing of the form input.
122
+		// For plugins to bypass normal processing here, they just need to return a truthy value.
123
+		if (
124
+			apply_filters(
125
+				'FHEE__EE_SPCO_Reg_Step_Attendee_Information___save_registration_form_input',
126
+				false,
127
+				$registration,
128
+				$form_input,
129
+				$input_value,
130
+				$this
131
+			)
132
+		) {
133
+			return true;
134
+		}
135
+		/*
136 136
          * $answer_cache_id is the key used to find the EE_Answer we want
137 137
          * @see https://events.codebasehq.com/projects/event-espresso/tickets/10477
138 138
          */
139
-        $answer_cache_id   = $this->checkout_reg_url_link
140
-            ? $form_input . '-' . $reg_url_link
141
-            : $form_input;
142
-        $registrant_answer = $this->registrant_data->getRegistrantAnswer($reg_url_link, $answer_cache_id);
143
-        $answer_is_obj     = $registrant_answer instanceof EE_Answer;
144
-        // rename form_inputs if they are EE_Attendee properties
145
-        switch ((string) $form_input) {
146
-            case 'state':
147
-            case 'STA_ID':
148
-                $attendee_property = true;
149
-                $form_input        = 'STA_ID';
150
-                break;
151
-
152
-            case 'country':
153
-            case 'CNT_ISO':
154
-                $attendee_property = true;
155
-                $form_input        = 'CNT_ISO';
156
-                break;
157
-
158
-            default:
159
-                $ATT_input         = 'ATT_' . $form_input;
160
-                $attendee_property = $this->attendee_model->has_field($ATT_input);
161
-                $form_input        = $attendee_property
162
-                    ? 'ATT_' . $form_input
163
-                    : $form_input;
164
-        }
165
-
166
-        // if this form input has a corresponding attendee property
167
-        if ($attendee_property) {
168
-            $this->registrant_data->addRegistrantDataValue($reg_url_link, $form_input, $input_value);
169
-            if ($answer_is_obj) {
170
-                // and delete the corresponding answer since we won't be storing this data in that object
171
-                $registration->_remove_relation_to($registrant_answer, 'Answer');
172
-                $registrant_answer->delete_permanently();
173
-            }
174
-            return true;
175
-        }
176
-        if ($answer_is_obj) {
177
-            // save this data to the answer object
178
-            $registrant_answer->set_value($input_value);
179
-            $result = $registrant_answer->save();
180
-            return $result !== false;
181
-        }
182
-        foreach ($this->registrant_data->registrantAnswers($reg_url_link) as $answer) {
183
-            if ($answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id) {
184
-                $answer->set_value($input_value);
185
-                $result = $answer->save();
186
-                return $result !== false;
187
-            }
188
-        }
189
-        return false;
190
-    }
191
-
192
-
193
-    /**
194
-     * @param int|string       $form_input
195
-     * @param float|int|string $input_value
196
-     * @return boolean
197
-     */
198
-    private function verifyCriticalAttendeeDetailsAreSetAndValidateEmail(
199
-        $form_input = '',
200
-        $input_value = ''
201
-    ): bool {
202
-        if (empty($input_value)) {
203
-            // if the form input isn't marked as being required, then just return
204
-            if (! isset($this->required_questions[ $form_input ]) || ! $this->required_questions[ $form_input ]) {
205
-                return true;
206
-            }
207
-            switch ($form_input) {
208
-                case 'fname':
209
-                    EE_Error::add_error(
210
-                        esc_html__('First Name is a required value.', 'event_espresso'),
211
-                        __FILE__,
212
-                        __FUNCTION__,
213
-                        __LINE__
214
-                    );
215
-                    return false;
216
-                case 'lname':
217
-                    EE_Error::add_error(
218
-                        esc_html__('Last Name is a required value.', 'event_espresso'),
219
-                        __FILE__,
220
-                        __FUNCTION__,
221
-                        __LINE__
222
-                    );
223
-                    return false;
224
-                case 'email':
225
-                    EE_Error::add_error(
226
-                        esc_html__('Please enter a valid email address.', 'event_espresso'),
227
-                        __FILE__,
228
-                        __FUNCTION__,
229
-                        __LINE__
230
-                    );
231
-                    return false;
232
-            }
233
-        }
234
-        return true;
235
-    }
139
+		$answer_cache_id   = $this->checkout_reg_url_link
140
+			? $form_input . '-' . $reg_url_link
141
+			: $form_input;
142
+		$registrant_answer = $this->registrant_data->getRegistrantAnswer($reg_url_link, $answer_cache_id);
143
+		$answer_is_obj     = $registrant_answer instanceof EE_Answer;
144
+		// rename form_inputs if they are EE_Attendee properties
145
+		switch ((string) $form_input) {
146
+			case 'state':
147
+			case 'STA_ID':
148
+				$attendee_property = true;
149
+				$form_input        = 'STA_ID';
150
+				break;
151
+
152
+			case 'country':
153
+			case 'CNT_ISO':
154
+				$attendee_property = true;
155
+				$form_input        = 'CNT_ISO';
156
+				break;
157
+
158
+			default:
159
+				$ATT_input         = 'ATT_' . $form_input;
160
+				$attendee_property = $this->attendee_model->has_field($ATT_input);
161
+				$form_input        = $attendee_property
162
+					? 'ATT_' . $form_input
163
+					: $form_input;
164
+		}
165
+
166
+		// if this form input has a corresponding attendee property
167
+		if ($attendee_property) {
168
+			$this->registrant_data->addRegistrantDataValue($reg_url_link, $form_input, $input_value);
169
+			if ($answer_is_obj) {
170
+				// and delete the corresponding answer since we won't be storing this data in that object
171
+				$registration->_remove_relation_to($registrant_answer, 'Answer');
172
+				$registrant_answer->delete_permanently();
173
+			}
174
+			return true;
175
+		}
176
+		if ($answer_is_obj) {
177
+			// save this data to the answer object
178
+			$registrant_answer->set_value($input_value);
179
+			$result = $registrant_answer->save();
180
+			return $result !== false;
181
+		}
182
+		foreach ($this->registrant_data->registrantAnswers($reg_url_link) as $answer) {
183
+			if ($answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id) {
184
+				$answer->set_value($input_value);
185
+				$result = $answer->save();
186
+				return $result !== false;
187
+			}
188
+		}
189
+		return false;
190
+	}
191
+
192
+
193
+	/**
194
+	 * @param int|string       $form_input
195
+	 * @param float|int|string $input_value
196
+	 * @return boolean
197
+	 */
198
+	private function verifyCriticalAttendeeDetailsAreSetAndValidateEmail(
199
+		$form_input = '',
200
+		$input_value = ''
201
+	): bool {
202
+		if (empty($input_value)) {
203
+			// if the form input isn't marked as being required, then just return
204
+			if (! isset($this->required_questions[ $form_input ]) || ! $this->required_questions[ $form_input ]) {
205
+				return true;
206
+			}
207
+			switch ($form_input) {
208
+				case 'fname':
209
+					EE_Error::add_error(
210
+						esc_html__('First Name is a required value.', 'event_espresso'),
211
+						__FILE__,
212
+						__FUNCTION__,
213
+						__LINE__
214
+					);
215
+					return false;
216
+				case 'lname':
217
+					EE_Error::add_error(
218
+						esc_html__('Last Name is a required value.', 'event_espresso'),
219
+						__FILE__,
220
+						__FUNCTION__,
221
+						__LINE__
222
+					);
223
+					return false;
224
+				case 'email':
225
+					EE_Error::add_error(
226
+						esc_html__('Please enter a valid email address.', 'event_espresso'),
227
+						__FILE__,
228
+						__FUNCTION__,
229
+						__LINE__
230
+					);
231
+					return false;
232
+			}
233
+		}
234
+		return true;
235
+	}
236 236
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
         $input_value
68 68
     ): bool {
69 69
         // check for critical inputs
70
-        if (! $this->verifyCriticalAttendeeDetailsAreSetAndValidateEmail($form_input, $input_value)) {
70
+        if ( ! $this->verifyCriticalAttendeeDetailsAreSetAndValidateEmail($form_input, $input_value)) {
71 71
             return false;
72 72
         }
73 73
         $input_value = $this->registrant_data->saveOrCopyPrimaryRegistrantData(
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
             $form_input,
76 76
             $input_value
77 77
         );
78
-        if (! $this->saveRegistrationFormInput($registration, $reg_url_link, $form_input, $input_value)) {
78
+        if ( ! $this->saveRegistrationFormInput($registration, $reg_url_link, $form_input, $input_value)) {
79 79
             EE_Error::add_error(
80 80
                 sprintf(
81 81
                     esc_html_x(
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
          * @see https://events.codebasehq.com/projects/event-espresso/tickets/10477
138 138
          */
139 139
         $answer_cache_id   = $this->checkout_reg_url_link
140
-            ? $form_input . '-' . $reg_url_link
140
+            ? $form_input.'-'.$reg_url_link
141 141
             : $form_input;
142 142
         $registrant_answer = $this->registrant_data->getRegistrantAnswer($reg_url_link, $answer_cache_id);
143 143
         $answer_is_obj     = $registrant_answer instanceof EE_Answer;
@@ -156,10 +156,10 @@  discard block
 block discarded – undo
156 156
                 break;
157 157
 
158 158
             default:
159
-                $ATT_input         = 'ATT_' . $form_input;
159
+                $ATT_input         = 'ATT_'.$form_input;
160 160
                 $attendee_property = $this->attendee_model->has_field($ATT_input);
161 161
                 $form_input        = $attendee_property
162
-                    ? 'ATT_' . $form_input
162
+                    ? 'ATT_'.$form_input
163 163
                     : $form_input;
164 164
         }
165 165
 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
     ): bool {
202 202
         if (empty($input_value)) {
203 203
             // if the form input isn't marked as being required, then just return
204
-            if (! isset($this->required_questions[ $form_input ]) || ! $this->required_questions[ $form_input ]) {
204
+            if ( ! isset($this->required_questions[$form_input]) || ! $this->required_questions[$form_input]) {
205 205
                 return true;
206 206
             }
207 207
             switch ($form_input) {
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormQuestionGroup.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -15,163 +15,163 @@
 block discarded – undo
15 15
 
16 16
 class RegFormQuestionGroup extends EE_Form_Section_Proper
17 17
 {
18
-    /**
19
-     * @var RegFormQuestionFactory
20
-     */
21
-    public $reg_form_question_factory;
18
+	/**
19
+	 * @var RegFormQuestionFactory
20
+	 */
21
+	public $reg_form_question_factory;
22 22
 
23 23
 
24
-    /**
25
-     * RegFormQuestionGroup constructor.
26
-     *
27
-     * @param EE_Registration        $registration
28
-     * @param EE_Question_Group      $question_group
29
-     * @param bool                   $admin_request
30
-     * @param RegFormQuestionFactory $reg_form_question_factory
31
-     * @throws EE_Error
32
-     * @throws ReflectionException
33
-     */
34
-    public function __construct(
35
-        EE_Registration $registration,
36
-        EE_Question_Group $question_group,
37
-        bool $admin_request,
38
-        RegFormQuestionFactory $reg_form_question_factory
39
-    ) {
40
-        $this->reg_form_question_factory = $reg_form_question_factory;
41
-        parent::__construct($this->generateFormArgs($registration, $question_group, $admin_request));
42
-    }
24
+	/**
25
+	 * RegFormQuestionGroup constructor.
26
+	 *
27
+	 * @param EE_Registration        $registration
28
+	 * @param EE_Question_Group      $question_group
29
+	 * @param bool                   $admin_request
30
+	 * @param RegFormQuestionFactory $reg_form_question_factory
31
+	 * @throws EE_Error
32
+	 * @throws ReflectionException
33
+	 */
34
+	public function __construct(
35
+		EE_Registration $registration,
36
+		EE_Question_Group $question_group,
37
+		bool $admin_request,
38
+		RegFormQuestionFactory $reg_form_question_factory
39
+	) {
40
+		$this->reg_form_question_factory = $reg_form_question_factory;
41
+		parent::__construct($this->generateFormArgs($registration, $question_group, $admin_request));
42
+	}
43 43
 
44 44
 
45
-    /**
46
-     * @param EE_Registration   $registration
47
-     * @param EE_Question_Group $question_group
48
-     * @param bool              $admin_request
49
-     * @return array
50
-     * @throws EE_Error
51
-     * @throws ReflectionException
52
-     */
53
-    private function generateFormArgs(
54
-        EE_Registration $registration,
55
-        EE_Question_Group $question_group,
56
-        bool $admin_request
57
-    ): array {
58
-        // array of params to pass to parent constructor
59
-        $form_args = [
60
-            'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-' . $registration->ID(),
61
-            'html_class'      => $admin_request
62
-                ? 'form-table ee-reg-form-qstn-grp-dv'
63
-                : 'ee-reg-form-qstn-grp-dv',
64
-            'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-'
65
-                                 . $registration->ID() . '-lbl',
66
-            'subsections'     => [
67
-                'reg_form_qstn_grp_hdr' => $this->questionGroupHeader($question_group, $admin_request),
68
-            ],
69
-            'layout_strategy' => $admin_request
70
-                ? new EE_Admin_Two_Column_Layout()
71
-                : new EE_Div_Per_Section_Layout(),
72
-        ];
73
-        // where params
74
-        $query_params = ['QST_deleted' => 0];
75
-        // don't load admin only questions on the frontend
76
-        if (! $admin_request) {
77
-            $query_params['QST_admin_only'] = ['!=', true];
78
-        }
79
-        $questions = $question_group->get_many_related(
80
-            'Question',
81
-            apply_filters(
82
-                'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__related_questions_query_params',
83
-                [
84
-                    $query_params,
85
-                    'order_by' => [
86
-                        'Question_Group_Question.QGQ_order' => 'ASC',
87
-                    ],
88
-                ],
89
-                $question_group,
90
-                $registration,
91
-                $this
92
-            )
93
-        );
94
-        // filter for additional content before questions
95
-        $form_args['subsections']['reg_form_questions_before'] = new EE_Form_Section_HTML(
96
-            apply_filters(
97
-                'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions',
98
-                '',
99
-                $registration,
100
-                $question_group,
101
-                $this
102
-            )
103
-        );
104
-        // loop thru questions
105
-        foreach ($questions as $question) {
106
-            if ($question instanceof EE_Question) {
107
-                $identifier = $question->is_system_question()
108
-                    ? $question->system_ID()
109
-                    : $question->ID();
45
+	/**
46
+	 * @param EE_Registration   $registration
47
+	 * @param EE_Question_Group $question_group
48
+	 * @param bool              $admin_request
49
+	 * @return array
50
+	 * @throws EE_Error
51
+	 * @throws ReflectionException
52
+	 */
53
+	private function generateFormArgs(
54
+		EE_Registration $registration,
55
+		EE_Question_Group $question_group,
56
+		bool $admin_request
57
+	): array {
58
+		// array of params to pass to parent constructor
59
+		$form_args = [
60
+			'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-' . $registration->ID(),
61
+			'html_class'      => $admin_request
62
+				? 'form-table ee-reg-form-qstn-grp-dv'
63
+				: 'ee-reg-form-qstn-grp-dv',
64
+			'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-'
65
+								 . $registration->ID() . '-lbl',
66
+			'subsections'     => [
67
+				'reg_form_qstn_grp_hdr' => $this->questionGroupHeader($question_group, $admin_request),
68
+			],
69
+			'layout_strategy' => $admin_request
70
+				? new EE_Admin_Two_Column_Layout()
71
+				: new EE_Div_Per_Section_Layout(),
72
+		];
73
+		// where params
74
+		$query_params = ['QST_deleted' => 0];
75
+		// don't load admin only questions on the frontend
76
+		if (! $admin_request) {
77
+			$query_params['QST_admin_only'] = ['!=', true];
78
+		}
79
+		$questions = $question_group->get_many_related(
80
+			'Question',
81
+			apply_filters(
82
+				'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__related_questions_query_params',
83
+				[
84
+					$query_params,
85
+					'order_by' => [
86
+						'Question_Group_Question.QGQ_order' => 'ASC',
87
+					],
88
+				],
89
+				$question_group,
90
+				$registration,
91
+				$this
92
+			)
93
+		);
94
+		// filter for additional content before questions
95
+		$form_args['subsections']['reg_form_questions_before'] = new EE_Form_Section_HTML(
96
+			apply_filters(
97
+				'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions',
98
+				'',
99
+				$registration,
100
+				$question_group,
101
+				$this
102
+			)
103
+		);
104
+		// loop thru questions
105
+		foreach ($questions as $question) {
106
+			if ($question instanceof EE_Question) {
107
+				$identifier = $question->is_system_question()
108
+					? $question->system_ID()
109
+					: $question->ID();
110 110
 
111
-                $form_args['subsections'][ $identifier ] = $this->reg_form_question_factory->create(
112
-                    $registration,
113
-                    $question
114
-                );
115
-            }
116
-        }
117
-        $form_args['subsections'] = apply_filters(
118
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information__question_group_reg_form__subsections_array',
119
-            $form_args['subsections'],
120
-            $registration,
121
-            $question_group,
122
-            $this
123
-        );
124
-        // filter for additional content after questions
125
-        $form_args['subsections']['reg_form_questions_after'] = new EE_Form_Section_HTML(
126
-            apply_filters(
127
-                'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions',
128
-                '',
129
-                $registration,
130
-                $question_group,
131
-                $this
132
-            )
133
-        );
111
+				$form_args['subsections'][ $identifier ] = $this->reg_form_question_factory->create(
112
+					$registration,
113
+					$question
114
+				);
115
+			}
116
+		}
117
+		$form_args['subsections'] = apply_filters(
118
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information__question_group_reg_form__subsections_array',
119
+			$form_args['subsections'],
120
+			$registration,
121
+			$question_group,
122
+			$this
123
+		);
124
+		// filter for additional content after questions
125
+		$form_args['subsections']['reg_form_questions_after'] = new EE_Form_Section_HTML(
126
+			apply_filters(
127
+				'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions',
128
+				'',
129
+				$registration,
130
+				$question_group,
131
+				$this
132
+			)
133
+		);
134 134
 
135
-        return $form_args;
136
-    }
135
+		return $form_args;
136
+	}
137 137
 
138 138
 
139
-    /**
140
-     * @param EE_Question_Group $question_group
141
-     * @param bool              $admin_request
142
-     * @return EE_Form_Section_HTML
143
-     */
144
-    private function questionGroupHeader(EE_Question_Group $question_group, bool $admin_request): EE_Form_Section_HTML
145
-    {
146
-        $html = '';
147
-        // group_name
148
-        if ($question_group->show_group_name() && $question_group->name() !== '') {
149
-            if ($admin_request) {
150
-                $html .= EEH_HTML::br();
151
-                $html .= EEH_HTML::h3(
152
-                    $question_group->name(),
153
-                    '',
154
-                    'ee-reg-form-qstn-grp-title title',
155
-                    'font-size: 1.3em; padding-left:0;'
156
-                );
157
-            } else {
158
-                $html .= EEH_HTML::h4(
159
-                    $question_group->name(),
160
-                    '',
161
-                    'ee-reg-form-qstn-grp-title section-title'
162
-                );
163
-            }
164
-        }
165
-        // group_desc
166
-        if ($question_group->show_group_desc() && $question_group->desc() !== '') {
167
-            $html .= EEH_HTML::p(
168
-                $question_group->desc(),
169
-                '',
170
-                $admin_request
171
-                    ? 'ee-reg-form-qstn-grp-desc-pg'
172
-                    : 'ee-reg-form-qstn-grp-desc-pg small-text lt-grey-text'
173
-            );
174
-        }
175
-        return new EE_Form_Section_HTML($html);
176
-    }
139
+	/**
140
+	 * @param EE_Question_Group $question_group
141
+	 * @param bool              $admin_request
142
+	 * @return EE_Form_Section_HTML
143
+	 */
144
+	private function questionGroupHeader(EE_Question_Group $question_group, bool $admin_request): EE_Form_Section_HTML
145
+	{
146
+		$html = '';
147
+		// group_name
148
+		if ($question_group->show_group_name() && $question_group->name() !== '') {
149
+			if ($admin_request) {
150
+				$html .= EEH_HTML::br();
151
+				$html .= EEH_HTML::h3(
152
+					$question_group->name(),
153
+					'',
154
+					'ee-reg-form-qstn-grp-title title',
155
+					'font-size: 1.3em; padding-left:0;'
156
+				);
157
+			} else {
158
+				$html .= EEH_HTML::h4(
159
+					$question_group->name(),
160
+					'',
161
+					'ee-reg-form-qstn-grp-title section-title'
162
+				);
163
+			}
164
+		}
165
+		// group_desc
166
+		if ($question_group->show_group_desc() && $question_group->desc() !== '') {
167
+			$html .= EEH_HTML::p(
168
+				$question_group->desc(),
169
+				'',
170
+				$admin_request
171
+					? 'ee-reg-form-qstn-grp-desc-pg'
172
+					: 'ee-reg-form-qstn-grp-desc-pg small-text lt-grey-text'
173
+			);
174
+		}
175
+		return new EE_Form_Section_HTML($html);
176
+	}
177 177
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -57,12 +57,12 @@  discard block
 block discarded – undo
57 57
     ): array {
58 58
         // array of params to pass to parent constructor
59 59
         $form_args = [
60
-            'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-' . $registration->ID(),
60
+            'html_id'         => 'ee-reg-form-qstn-grp-'.$question_group->identifier().'-'.$registration->ID(),
61 61
             'html_class'      => $admin_request
62 62
                 ? 'form-table ee-reg-form-qstn-grp-dv'
63 63
                 : 'ee-reg-form-qstn-grp-dv',
64
-            'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-'
65
-                                 . $registration->ID() . '-lbl',
64
+            'html_label_id'   => 'ee-reg-form-qstn-grp-'.$question_group->identifier().'-'
65
+                                 . $registration->ID().'-lbl',
66 66
             'subsections'     => [
67 67
                 'reg_form_qstn_grp_hdr' => $this->questionGroupHeader($question_group, $admin_request),
68 68
             ],
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
         // where params
74 74
         $query_params = ['QST_deleted' => 0];
75 75
         // don't load admin only questions on the frontend
76
-        if (! $admin_request) {
76
+        if ( ! $admin_request) {
77 77
             $query_params['QST_admin_only'] = ['!=', true];
78 78
         }
79 79
         $questions = $question_group->get_many_related(
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
                     ? $question->system_ID()
109 109
                     : $question->ID();
110 110
 
111
-                $form_args['subsections'][ $identifier ] = $this->reg_form_question_factory->create(
111
+                $form_args['subsections'][$identifier] = $this->reg_form_question_factory->create(
112 112
                     $registration,
113 113
                     $question
114 114
                 );
Please login to merge, or discard this patch.
core/domain/services/registration/form/v1/RegFormHandler.php 2 patches
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
         $required_questions = $reg_form instanceof RegForm ? $reg_form->requiredQuestions() : [];
84 84
         $this->input_handler = LoaderFactory::getShared(
85 85
             RegFormInputHandler::class,
86
-            [ $this->checkout->reg_url_link, $required_questions ]
86
+            [$this->checkout->reg_url_link, $required_questions]
87 87
         );
88 88
 
89 89
     }
@@ -126,21 +126,21 @@  discard block
 block discarded – undo
126 126
         $this->valid = true;
127 127
         foreach ($registrations as $registration) {
128 128
             // verify EE_Registration object
129
-            if (! $this->isValidRegistration($registration)) {
129
+            if ( ! $this->isValidRegistration($registration)) {
130 130
                 return $this->isInvalid();
131 131
             }
132 132
             $reg_url_link = $registration->reg_url_link();
133 133
             // reg_url_link exists ?
134
-            if (! $this->isValidRegUrlLink($reg_url_link)) {
134
+            if ( ! $this->isValidRegUrlLink($reg_url_link)) {
135 135
                 return $this->isInvalid();
136 136
             }
137 137
             // should this registration be processed during this visit ?
138
-            if (! $this->checkout->visit_allows_processing_of_this_registration($registration)) {
138
+            if ( ! $this->checkout->visit_allows_processing_of_this_registration($registration)) {
139 139
                 continue;
140 140
             }
141 141
             // if NOT revisiting, then let's save the registration now,
142 142
             // so that we have a REG_ID to use when generating other objects
143
-            if (! $this->checkout->revisit) {
143
+            if ( ! $this->checkout->revisit) {
144 144
                 $registration->save();
145 145
             }
146 146
             /**
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
             }
165 165
 
166 166
             // Houston, we have a registration!
167
-            if (! $this->processRegistration($registration, $reg_url_link, $reg_form_data)) {
167
+            if ( ! $this->processRegistration($registration, $reg_url_link, $reg_form_data)) {
168 168
                 return $this->isInvalid();
169 169
             }
170 170
         }
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
      */
179 179
     private function isValidRegUrlLink(string $reg_url_link): bool
180 180
     {
181
-        if (! empty($reg_url_link)) {
181
+        if ( ! empty($reg_url_link)) {
182 182
             return true;
183 183
         }
184 184
         EE_Error::add_error(
@@ -231,11 +231,11 @@  discard block
 block discarded – undo
231 231
         array $reg_form_data
232 232
     ): bool {
233 233
         $this->registrant_data->initializeRegistrantData($registration);
234
-        if (! $this->processRegFormData($registration, $reg_url_link, $reg_form_data)) {
234
+        if ( ! $this->processRegFormData($registration, $reg_url_link, $reg_form_data)) {
235 235
             return false;
236 236
         }
237 237
         // RegFormAttendeeFactory
238
-        if (! $this->attendee_factory->create($registration, $reg_url_link)) {
238
+        if ( ! $this->attendee_factory->create($registration, $reg_url_link)) {
239 239
             return false;
240 240
         }
241 241
         // at this point, we should have enough details about the registrant to consider the registration
@@ -272,15 +272,15 @@  discard block
 block discarded – undo
272 272
      */
273 273
     private function processRegFormData(EE_Registration $registration, string $reg_url_link, array $reg_form_data): bool
274 274
     {
275
-        if (isset($reg_form_data[ $reg_url_link ])) {
275
+        if (isset($reg_form_data[$reg_url_link])) {
276 276
             // do we need to copy basic info from primary attendee ?
277
-            $copy_primary = isset($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info'])
278
-                                  && absint($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info']) === 0;
277
+            $copy_primary = isset($reg_form_data[$reg_url_link]['additional_attendee_reg_info'])
278
+                                  && absint($reg_form_data[$reg_url_link]['additional_attendee_reg_info']) === 0;
279 279
             $this->registrant_data->setCopyPrimary($copy_primary);
280 280
             // filter form input data for this registration
281
-            $reg_form_data[ $reg_url_link ] = (array) apply_filters(
281
+            $reg_form_data[$reg_url_link] = (array) apply_filters(
282 282
                 'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
283
-                $reg_form_data[ $reg_url_link ]
283
+                $reg_form_data[$reg_url_link]
284 284
             );
285 285
             if (isset($reg_form_data['primary_attendee'])) {
286 286
                 $primary_reg_url_link = $reg_form_data['primary_attendee'] ?? '';
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
                 unset($reg_form_data['primary_attendee']);
289 289
             }
290 290
             // now loop through our array of valid post data && process attendee reg forms
291
-            foreach ($reg_form_data[ $reg_url_link ] as $form_section => $form_inputs) {
291
+            foreach ($reg_form_data[$reg_url_link] as $form_section => $form_inputs) {
292 292
                 if (in_array($form_section, $this->non_input_form_sections, true)) {
293 293
                     continue;
294 294
                 }
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
                         $form_input,
300 300
                         $input_value
301 301
                     );
302
-                    if (! $input_processed) {
302
+                    if ( ! $input_processed) {
303 303
                         return false;
304 304
                     }
305 305
                 }
Please login to merge, or discard this patch.
Indentation   +278 added lines, -278 removed lines patch added patch discarded remove patch
@@ -18,309 +18,309 @@
 block discarded – undo
18 18
 class RegFormHandler
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Checkout
23
-     */
24
-    public $checkout;
21
+	/**
22
+	 * @var EE_Checkout
23
+	 */
24
+	public $checkout;
25 25
 
26
-    /**
27
-     * @var RegFormInputHandler
28
-     */
29
-    public $input_handler;
26
+	/**
27
+	 * @var RegFormInputHandler
28
+	 */
29
+	public $input_handler;
30 30
 
31
-    /**
32
-     * @var array
33
-     */
34
-    private $non_input_form_sections;
31
+	/**
32
+	 * @var array
33
+	 */
34
+	private $non_input_form_sections;
35 35
 
36
-    /**
37
-     * @var RegFormAttendeeFactory
38
-     */
39
-    private $attendee_factory;
36
+	/**
37
+	 * @var RegFormAttendeeFactory
38
+	 */
39
+	private $attendee_factory;
40 40
 
41
-    /**
42
-     * @var RegistrantData
43
-     */
44
-    private $registrant_data;
41
+	/**
42
+	 * @var RegistrantData
43
+	 */
44
+	private $registrant_data;
45 45
 
46
-    /**
47
-     * @var EE_Registration_Processor
48
-     */
49
-    private $registration_processor;
46
+	/**
47
+	 * @var EE_Registration_Processor
48
+	 */
49
+	private $registration_processor;
50 50
 
51
-    /**
52
-     * @var bool
53
-     */
54
-    private $valid;
51
+	/**
52
+	 * @var bool
53
+	 */
54
+	private $valid;
55 55
 
56 56
 
57
-    /**
58
-     * RegFormHandler constructor.
59
-     */
60
-    public function __construct(
61
-        EE_Checkout $checkout,
62
-        RegistrantData $registrant_data,
63
-        RegFormAttendeeFactory $attendee_factory,
64
-        EE_Registration_Processor $registration_processor
65
-    ) {
66
-        $this->checkout                = $checkout;
67
-        $this->registrant_data         = $registrant_data;
68
-        $this->attendee_factory        = $attendee_factory;
69
-        $this->registration_processor  = $registration_processor;
70
-        // reg form sections that do not contain inputs
71
-        $this->non_input_form_sections = [
72
-            'primary_registrant_data',
73
-            'additional_attendee_reg_info',
74
-            'spco_copy_attendee_chk',
75
-        ];
76
-        $this->initializeInputHandler();
77
-    }
57
+	/**
58
+	 * RegFormHandler constructor.
59
+	 */
60
+	public function __construct(
61
+		EE_Checkout $checkout,
62
+		RegistrantData $registrant_data,
63
+		RegFormAttendeeFactory $attendee_factory,
64
+		EE_Registration_Processor $registration_processor
65
+	) {
66
+		$this->checkout                = $checkout;
67
+		$this->registrant_data         = $registrant_data;
68
+		$this->attendee_factory        = $attendee_factory;
69
+		$this->registration_processor  = $registration_processor;
70
+		// reg form sections that do not contain inputs
71
+		$this->non_input_form_sections = [
72
+			'primary_registrant_data',
73
+			'additional_attendee_reg_info',
74
+			'spco_copy_attendee_chk',
75
+		];
76
+		$this->initializeInputHandler();
77
+	}
78 78
 
79 79
 
80
-    private function initializeInputHandler()
81
-    {
82
-        $reg_form = $this->checkout->current_step->reg_form;
83
-        $required_questions = $reg_form instanceof RegForm ? $reg_form->requiredQuestions() : [];
84
-        $this->input_handler = LoaderFactory::getShared(
85
-            RegFormInputHandler::class,
86
-            [ $this->checkout->reg_url_link, $required_questions ]
87
-        );
88
-    }
80
+	private function initializeInputHandler()
81
+	{
82
+		$reg_form = $this->checkout->current_step->reg_form;
83
+		$required_questions = $reg_form instanceof RegForm ? $reg_form->requiredQuestions() : [];
84
+		$this->input_handler = LoaderFactory::getShared(
85
+			RegFormInputHandler::class,
86
+			[ $this->checkout->reg_url_link, $required_questions ]
87
+		);
88
+	}
89 89
 
90 90
 
91
-    /**
92
-     * @return int
93
-     */
94
-    public function attendeeCount(): int
95
-    {
96
-        return $this->registrant_data->attendeeCount();
97
-    }
91
+	/**
92
+	 * @return int
93
+	 */
94
+	public function attendeeCount(): int
95
+	{
96
+		return $this->registrant_data->attendeeCount();
97
+	}
98 98
 
99 99
 
100
-    /**
101
-     * @return bool
102
-     */
103
-    private function isInvalid(): bool
104
-    {
105
-        $this->valid = false;
106
-        return $this->valid;
107
-    }
100
+	/**
101
+	 * @return bool
102
+	 */
103
+	private function isInvalid(): bool
104
+	{
105
+		$this->valid = false;
106
+		return $this->valid;
107
+	}
108 108
 
109 109
 
110
-    /**
111
-     * @param EE_Registration[] $registrations
112
-     * @param array[][]         $reg_form_data
113
-     * @return bool
114
-     * @throws EntityNotFoundException
115
-     * @throws EE_Error
116
-     * @throws InvalidArgumentException
117
-     * @throws ReflectionException
118
-     * @throws RuntimeException
119
-     * @throws InvalidDataTypeException
120
-     * @throws InvalidInterfaceException
121
-     */
122
-    public function processRegistrations(array $registrations, array $reg_form_data): bool
123
-    {
124
-        // start off optimistic, then trip this to false if anything goes wrong
125
-        $this->valid = true;
126
-        foreach ($registrations as $registration) {
127
-            // verify EE_Registration object
128
-            if (! $this->isValidRegistration($registration)) {
129
-                return $this->isInvalid();
130
-            }
131
-            $reg_url_link = $registration->reg_url_link();
132
-            // reg_url_link exists ?
133
-            if (! $this->isValidRegUrlLink($reg_url_link)) {
134
-                return $this->isInvalid();
135
-            }
136
-            // should this registration be processed during this visit ?
137
-            if (! $this->checkout->visit_allows_processing_of_this_registration($registration)) {
138
-                continue;
139
-            }
140
-            // if NOT revisiting, then let's save the registration now,
141
-            // so that we have a REG_ID to use when generating other objects
142
-            if (! $this->checkout->revisit) {
143
-                $registration->save();
144
-            }
145
-            /**
146
-             * This allows plugins to trigger a fail on processing of a
147
-             * registration for any conditions they may have for it to pass.
148
-             *
149
-             * @var bool if true is returned by the plugin then the registration processing is halted.
150
-             */
151
-            if (
152
-                apply_filters(
153
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___process_registrations__pre_registration_process',
154
-                    false,
155
-                    $this->registrant_data->attendeeCount(),
156
-                    $registration,
157
-                    $registrations,
158
-                    $reg_form_data,
159
-                    $this
160
-                )
161
-            ) {
162
-                return $this->isInvalid();
163
-            }
110
+	/**
111
+	 * @param EE_Registration[] $registrations
112
+	 * @param array[][]         $reg_form_data
113
+	 * @return bool
114
+	 * @throws EntityNotFoundException
115
+	 * @throws EE_Error
116
+	 * @throws InvalidArgumentException
117
+	 * @throws ReflectionException
118
+	 * @throws RuntimeException
119
+	 * @throws InvalidDataTypeException
120
+	 * @throws InvalidInterfaceException
121
+	 */
122
+	public function processRegistrations(array $registrations, array $reg_form_data): bool
123
+	{
124
+		// start off optimistic, then trip this to false if anything goes wrong
125
+		$this->valid = true;
126
+		foreach ($registrations as $registration) {
127
+			// verify EE_Registration object
128
+			if (! $this->isValidRegistration($registration)) {
129
+				return $this->isInvalid();
130
+			}
131
+			$reg_url_link = $registration->reg_url_link();
132
+			// reg_url_link exists ?
133
+			if (! $this->isValidRegUrlLink($reg_url_link)) {
134
+				return $this->isInvalid();
135
+			}
136
+			// should this registration be processed during this visit ?
137
+			if (! $this->checkout->visit_allows_processing_of_this_registration($registration)) {
138
+				continue;
139
+			}
140
+			// if NOT revisiting, then let's save the registration now,
141
+			// so that we have a REG_ID to use when generating other objects
142
+			if (! $this->checkout->revisit) {
143
+				$registration->save();
144
+			}
145
+			/**
146
+			 * This allows plugins to trigger a fail on processing of a
147
+			 * registration for any conditions they may have for it to pass.
148
+			 *
149
+			 * @var bool if true is returned by the plugin then the registration processing is halted.
150
+			 */
151
+			if (
152
+				apply_filters(
153
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___process_registrations__pre_registration_process',
154
+					false,
155
+					$this->registrant_data->attendeeCount(),
156
+					$registration,
157
+					$registrations,
158
+					$reg_form_data,
159
+					$this
160
+				)
161
+			) {
162
+				return $this->isInvalid();
163
+			}
164 164
 
165
-            // Houston, we have a registration!
166
-            if (! $this->processRegistration($registration, $reg_url_link, $reg_form_data)) {
167
-                return $this->isInvalid();
168
-            }
169
-        }
170
-        return $this->valid;
171
-    }
165
+			// Houston, we have a registration!
166
+			if (! $this->processRegistration($registration, $reg_url_link, $reg_form_data)) {
167
+				return $this->isInvalid();
168
+			}
169
+		}
170
+		return $this->valid;
171
+	}
172 172
 
173 173
 
174
-    /**
175
-     * @param string $reg_url_link
176
-     * @return bool
177
-     */
178
-    private function isValidRegUrlLink(string $reg_url_link): bool
179
-    {
180
-        if (! empty($reg_url_link)) {
181
-            return true;
182
-        }
183
-        EE_Error::add_error(
184
-            esc_html__(
185
-                'An invalid or missing line item ID was encountered while attempting to process the registration form.',
186
-                'event_espresso'
187
-            ),
188
-            __FILE__,
189
-            __FUNCTION__,
190
-            __LINE__
191
-        );
192
-        return false;
193
-    }
174
+	/**
175
+	 * @param string $reg_url_link
176
+	 * @return bool
177
+	 */
178
+	private function isValidRegUrlLink(string $reg_url_link): bool
179
+	{
180
+		if (! empty($reg_url_link)) {
181
+			return true;
182
+		}
183
+		EE_Error::add_error(
184
+			esc_html__(
185
+				'An invalid or missing line item ID was encountered while attempting to process the registration form.',
186
+				'event_espresso'
187
+			),
188
+			__FILE__,
189
+			__FUNCTION__,
190
+			__LINE__
191
+		);
192
+		return false;
193
+	}
194 194
 
195 195
 
196
-    /**
197
-     * @param EE_Registration $registration
198
-     * @return bool
199
-     */
200
-    private function isValidRegistration(EE_Registration $registration): bool
201
-    {
202
-        // verify EE_Registration object
203
-        if ($registration instanceof EE_Registration) {
204
-            return true;
205
-        }
206
-        EE_Error::add_error(
207
-            esc_html__(
208
-                'An invalid Registration object was discovered when attempting to process your registration information.',
209
-                'event_espresso'
210
-            ),
211
-            __FILE__,
212
-            __FUNCTION__,
213
-            __LINE__
214
-        );
215
-        return false;
216
-    }
196
+	/**
197
+	 * @param EE_Registration $registration
198
+	 * @return bool
199
+	 */
200
+	private function isValidRegistration(EE_Registration $registration): bool
201
+	{
202
+		// verify EE_Registration object
203
+		if ($registration instanceof EE_Registration) {
204
+			return true;
205
+		}
206
+		EE_Error::add_error(
207
+			esc_html__(
208
+				'An invalid Registration object was discovered when attempting to process your registration information.',
209
+				'event_espresso'
210
+			),
211
+			__FILE__,
212
+			__FUNCTION__,
213
+			__LINE__
214
+		);
215
+		return false;
216
+	}
217 217
 
218 218
 
219
-    /**
220
-     * @param EE_Registration $registration
221
-     * @param string          $reg_url_link
222
-     * @param array[][]       $reg_form_data
223
-     * @return bool
224
-     * @throws EE_Error
225
-     * @throws ReflectionException
226
-     */
227
-    private function processRegistration(
228
-        EE_Registration $registration,
229
-        string $reg_url_link,
230
-        array $reg_form_data
231
-    ): bool {
232
-        $this->registrant_data->initializeRegistrantData($registration);
233
-        if (! $this->processRegFormData($registration, $reg_url_link, $reg_form_data)) {
234
-            return false;
235
-        }
236
-        // RegFormAttendeeFactory
237
-        if (! $this->attendee_factory->create($registration, $reg_url_link)) {
238
-            return false;
239
-        }
240
-        // at this point, we should have enough details about the registrant to consider the registration
241
-        // NOT incomplete
242
-        $this->registration_processor->toggle_incomplete_registration_status_to_default(
243
-            $registration,
244
-            false,
245
-            new Context(
246
-                'spco_reg_step_attendee_information_process_registrations',
247
-                esc_html__(
248
-                    'Finished populating registration with details from the registration form after submitting the Attendee Information Reg Step.',
249
-                    'event_espresso'
250
-                )
251
-            )
252
-        );
253
-        // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to
254
-        // abandoned
255
-        $this->checkout->transaction->toggle_failed_transaction_status();
256
-        // if we've gotten this far, then let's save what we have
257
-        $registration->save();
258
-        // add relation between TXN and registration
259
-        $this->associateRegistrationWithTransaction($registration);
260
-        return true;
261
-    }
219
+	/**
220
+	 * @param EE_Registration $registration
221
+	 * @param string          $reg_url_link
222
+	 * @param array[][]       $reg_form_data
223
+	 * @return bool
224
+	 * @throws EE_Error
225
+	 * @throws ReflectionException
226
+	 */
227
+	private function processRegistration(
228
+		EE_Registration $registration,
229
+		string $reg_url_link,
230
+		array $reg_form_data
231
+	): bool {
232
+		$this->registrant_data->initializeRegistrantData($registration);
233
+		if (! $this->processRegFormData($registration, $reg_url_link, $reg_form_data)) {
234
+			return false;
235
+		}
236
+		// RegFormAttendeeFactory
237
+		if (! $this->attendee_factory->create($registration, $reg_url_link)) {
238
+			return false;
239
+		}
240
+		// at this point, we should have enough details about the registrant to consider the registration
241
+		// NOT incomplete
242
+		$this->registration_processor->toggle_incomplete_registration_status_to_default(
243
+			$registration,
244
+			false,
245
+			new Context(
246
+				'spco_reg_step_attendee_information_process_registrations',
247
+				esc_html__(
248
+					'Finished populating registration with details from the registration form after submitting the Attendee Information Reg Step.',
249
+					'event_espresso'
250
+				)
251
+			)
252
+		);
253
+		// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to
254
+		// abandoned
255
+		$this->checkout->transaction->toggle_failed_transaction_status();
256
+		// if we've gotten this far, then let's save what we have
257
+		$registration->save();
258
+		// add relation between TXN and registration
259
+		$this->associateRegistrationWithTransaction($registration);
260
+		return true;
261
+	}
262 262
 
263 263
 
264
-    /**
265
-     * @param EE_Registration $registration
266
-     * @param string          $reg_url_link
267
-     * @param array           $reg_form_data
268
-     * @return bool
269
-     * @throws EE_Error
270
-     * @throws ReflectionException
271
-     */
272
-    private function processRegFormData(EE_Registration $registration, string $reg_url_link, array $reg_form_data): bool
273
-    {
274
-        if (isset($reg_form_data[ $reg_url_link ])) {
275
-            // do we need to copy basic info from primary attendee ?
276
-            $copy_primary = isset($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info'])
277
-                                  && absint($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info']) === 0;
278
-            $this->registrant_data->setCopyPrimary($copy_primary);
279
-            // filter form input data for this registration
280
-            $reg_form_data[ $reg_url_link ] = (array) apply_filters(
281
-                'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
282
-                $reg_form_data[ $reg_url_link ]
283
-            );
284
-            if (isset($reg_form_data['primary_attendee'])) {
285
-                $primary_reg_url_link = $reg_form_data['primary_attendee'] ?? '';
286
-                $this->registrant_data->addPrimaryRegistrantDataValue('reg_url_link', $primary_reg_url_link);
287
-                unset($reg_form_data['primary_attendee']);
288
-            }
289
-            // now loop through our array of valid post data && process attendee reg forms
290
-            foreach ($reg_form_data[ $reg_url_link ] as $form_section => $form_inputs) {
291
-                if (in_array($form_section, $this->non_input_form_sections, true)) {
292
-                    continue;
293
-                }
294
-                foreach ($form_inputs as $form_input => $input_value) {
295
-                    $input_processed = $this->input_handler->processFormInput(
296
-                        $registration,
297
-                        $reg_url_link,
298
-                        $form_input,
299
-                        $input_value
300
-                    );
301
-                    if (! $input_processed) {
302
-                        return false;
303
-                    }
304
-                }
305
-            }
306
-        }
307
-        return true;
308
-    }
264
+	/**
265
+	 * @param EE_Registration $registration
266
+	 * @param string          $reg_url_link
267
+	 * @param array           $reg_form_data
268
+	 * @return bool
269
+	 * @throws EE_Error
270
+	 * @throws ReflectionException
271
+	 */
272
+	private function processRegFormData(EE_Registration $registration, string $reg_url_link, array $reg_form_data): bool
273
+	{
274
+		if (isset($reg_form_data[ $reg_url_link ])) {
275
+			// do we need to copy basic info from primary attendee ?
276
+			$copy_primary = isset($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info'])
277
+								  && absint($reg_form_data[ $reg_url_link ]['additional_attendee_reg_info']) === 0;
278
+			$this->registrant_data->setCopyPrimary($copy_primary);
279
+			// filter form input data for this registration
280
+			$reg_form_data[ $reg_url_link ] = (array) apply_filters(
281
+				'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
282
+				$reg_form_data[ $reg_url_link ]
283
+			);
284
+			if (isset($reg_form_data['primary_attendee'])) {
285
+				$primary_reg_url_link = $reg_form_data['primary_attendee'] ?? '';
286
+				$this->registrant_data->addPrimaryRegistrantDataValue('reg_url_link', $primary_reg_url_link);
287
+				unset($reg_form_data['primary_attendee']);
288
+			}
289
+			// now loop through our array of valid post data && process attendee reg forms
290
+			foreach ($reg_form_data[ $reg_url_link ] as $form_section => $form_inputs) {
291
+				if (in_array($form_section, $this->non_input_form_sections, true)) {
292
+					continue;
293
+				}
294
+				foreach ($form_inputs as $form_input => $input_value) {
295
+					$input_processed = $this->input_handler->processFormInput(
296
+						$registration,
297
+						$reg_url_link,
298
+						$form_input,
299
+						$input_value
300
+					);
301
+					if (! $input_processed) {
302
+						return false;
303
+					}
304
+				}
305
+			}
306
+		}
307
+		return true;
308
+	}
309 309
 
310 310
 
311
-    /**
312
-     * @param EE_Registration $registration
313
-     * @return void
314
-     * @throws EE_Error
315
-     * @throws InvalidArgumentException
316
-     * @throws ReflectionException
317
-     * @throws InvalidDataTypeException
318
-     * @throws InvalidInterfaceException
319
-     */
320
-    private function associateRegistrationWithTransaction(EE_Registration $registration)
321
-    {
322
-        // add relation to registration
323
-        $this->checkout->transaction->_add_relation_to($registration, 'Registration');
324
-        $this->checkout->transaction->update_cache_after_object_save('Registration', $registration);
325
-    }
311
+	/**
312
+	 * @param EE_Registration $registration
313
+	 * @return void
314
+	 * @throws EE_Error
315
+	 * @throws InvalidArgumentException
316
+	 * @throws ReflectionException
317
+	 * @throws InvalidDataTypeException
318
+	 * @throws InvalidInterfaceException
319
+	 */
320
+	private function associateRegistrationWithTransaction(EE_Registration $registration)
321
+	{
322
+		// add relation to registration
323
+		$this->checkout->transaction->_add_relation_to($registration, 'Registration');
324
+		$this->checkout->transaction->update_cache_after_object_save('Registration', $registration);
325
+	}
326 326
 }
Please login to merge, or discard this patch.