Completed
Pull Request — master (#378)
by Darren
19:13
created
core/libraries/rest_api/controllers/rpc/Checkin.php 2 patches
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -26,124 +26,124 @@
 block discarded – undo
26 26
 class Checkin extends Base
27 27
 {
28 28
 
29
-    /**
30
-     * @param WP_REST_Request $request
31
-     * @param string          $version
32
-     * @return WP_Error|WP_REST_Response
33
-     */
34
-    public static function handleRequestToggleCheckin(WP_REST_Request $request, $version)
35
-    {
36
-        $controller = new Checkin();
37
-        return $controller->createCheckinCheckoutObject($request, $version);
38
-    }
29
+	/**
30
+	 * @param WP_REST_Request $request
31
+	 * @param string          $version
32
+	 * @return WP_Error|WP_REST_Response
33
+	 */
34
+	public static function handleRequestToggleCheckin(WP_REST_Request $request, $version)
35
+	{
36
+		$controller = new Checkin();
37
+		return $controller->createCheckinCheckoutObject($request, $version);
38
+	}
39 39
 
40 40
 
41
-    /**
42
-     * Toggles whether the user is checked in or not.
43
-     *
44
-     * @param WP_REST_Request $request
45
-     * @param string          $version
46
-     * @return WP_Error|WP_REST_Response
47
-     */
48
-    protected function createCheckinCheckoutObject(WP_REST_Request $request, $version)
49
-    {
50
-        $reg_id = $request->get_param('REG_ID');
51
-        $dtt_id = $request->get_param('DTT_ID');
52
-        $force = $request->get_param('force');
53
-        if ($force == 'true') {
54
-            $force = true;
55
-        } else {
56
-            $force = false;
57
-        }
58
-        $reg = EEM_Registration::instance()->get_one_by_ID($reg_id);
59
-        if (! $reg instanceof EE_Registration) {
60
-            return $this->sendResponse(
61
-                new WP_Error(
62
-                    'rest_registration_toggle_checkin_invalid_id',
63
-                    sprintf(
64
-                        __(
65
-                            'You cannot checkin registration with ID %1$s because it doesn\'t exist.',
66
-                            'event_espresso'
67
-                        ),
68
-                        $reg_id
69
-                    ),
70
-                    array('status' => 422)
71
-                )
72
-            );
73
-        }
74
-        if (! EE_Capabilities::instance()->current_user_can('ee_edit_checkin', 'rest_api_checkin_endpoint', $reg_id)) {
75
-            return $this->sendResponse(
76
-                new WP_Error(
77
-                    'rest_user_cannot_toggle_checkin',
78
-                    sprintf(
79
-                        __('You are not allowed to checkin registration with ID %1$s.', 'event_espresso'),
80
-                        $reg_id
81
-                    ),
82
-                    array('status' => 403)
83
-                )
84
-            );
85
-        }
86
-        $success = $reg->toggle_checkin_status($dtt_id, ! $force);
87
-        if ($success === false) {
88
-            // check if we know they can't check in because they're not approved and we aren't forcing
89
-            if (! $reg->is_approved() && ! $force) {
90
-                // rely on EE_Error::add_error messages to have been added to give more data about why it failed
91
-                return $this->sendResponse(
92
-                    new WP_Error(
93
-                        'rest_toggle_checkin_failed',
94
-                        __(
95
-                        // @codingStandardsIgnoreStart
96
-                            'Registration check-in failed because the registration is not approved. You may attempt to force checking in though.',
97
-                            // @codingStandardsIgnoreEnd
98
-                            'event_espresso'
99
-                        )
100
-                    )
101
-                );
102
-            }
103
-            return $this->sendResponse(
104
-                new WP_Error(
105
-                    'rest_toggle_checkin_failed_not_forceable',
106
-                    __('Registration checkin failed. Please see additional error data.', 'event_espresso')
107
-                )
108
-            );
109
-        }
110
-        $checkin = EEM_Checkin::instance()->get_one(
111
-            array(
112
-                array(
113
-                    'REG_ID' => $reg_id,
114
-                    'DTT_ID' => $dtt_id,
115
-                ),
116
-                'order_by' => array(
117
-                    'CHK_timestamp' => 'DESC',
118
-                ),
119
-            )
120
-        );
121
-        if (! $checkin instanceof EE_Checkin) {
122
-            return $this->sendResponse(
123
-                new WP_Error(
124
-                    'rest_toggle_checkin_error',
125
-                    sprintf(
126
-                        __(
127
-                        // @codingStandardsIgnoreStart
128
-                            'Supposedly we created a new checkin object for registration %1$s at datetime %2$s, but we can\'t find it.',
129
-                            // @codingStandardsIgnoreEnd
130
-                            'event_espresso'
131
-                        ),
132
-                        $reg_id,
133
-                        $dtt_id
134
-                    )
135
-                )
136
-            );
137
-        }
138
-        $get_request = new WP_REST_Request(
139
-            'GET',
140
-            '/' . EED_Core_Rest_Api::ee_api_namespace . 'v' . $version . '/checkins/' . $checkin->ID()
141
-        );
142
-        $get_request->set_url_params(
143
-            array(
144
-                'id' => $checkin->ID(),
145
-            )
146
-        );
147
-        return Read::handleRequestGetOne($get_request, $version, 'Checkin');
148
-    }
41
+	/**
42
+	 * Toggles whether the user is checked in or not.
43
+	 *
44
+	 * @param WP_REST_Request $request
45
+	 * @param string          $version
46
+	 * @return WP_Error|WP_REST_Response
47
+	 */
48
+	protected function createCheckinCheckoutObject(WP_REST_Request $request, $version)
49
+	{
50
+		$reg_id = $request->get_param('REG_ID');
51
+		$dtt_id = $request->get_param('DTT_ID');
52
+		$force = $request->get_param('force');
53
+		if ($force == 'true') {
54
+			$force = true;
55
+		} else {
56
+			$force = false;
57
+		}
58
+		$reg = EEM_Registration::instance()->get_one_by_ID($reg_id);
59
+		if (! $reg instanceof EE_Registration) {
60
+			return $this->sendResponse(
61
+				new WP_Error(
62
+					'rest_registration_toggle_checkin_invalid_id',
63
+					sprintf(
64
+						__(
65
+							'You cannot checkin registration with ID %1$s because it doesn\'t exist.',
66
+							'event_espresso'
67
+						),
68
+						$reg_id
69
+					),
70
+					array('status' => 422)
71
+				)
72
+			);
73
+		}
74
+		if (! EE_Capabilities::instance()->current_user_can('ee_edit_checkin', 'rest_api_checkin_endpoint', $reg_id)) {
75
+			return $this->sendResponse(
76
+				new WP_Error(
77
+					'rest_user_cannot_toggle_checkin',
78
+					sprintf(
79
+						__('You are not allowed to checkin registration with ID %1$s.', 'event_espresso'),
80
+						$reg_id
81
+					),
82
+					array('status' => 403)
83
+				)
84
+			);
85
+		}
86
+		$success = $reg->toggle_checkin_status($dtt_id, ! $force);
87
+		if ($success === false) {
88
+			// check if we know they can't check in because they're not approved and we aren't forcing
89
+			if (! $reg->is_approved() && ! $force) {
90
+				// rely on EE_Error::add_error messages to have been added to give more data about why it failed
91
+				return $this->sendResponse(
92
+					new WP_Error(
93
+						'rest_toggle_checkin_failed',
94
+						__(
95
+						// @codingStandardsIgnoreStart
96
+							'Registration check-in failed because the registration is not approved. You may attempt to force checking in though.',
97
+							// @codingStandardsIgnoreEnd
98
+							'event_espresso'
99
+						)
100
+					)
101
+				);
102
+			}
103
+			return $this->sendResponse(
104
+				new WP_Error(
105
+					'rest_toggle_checkin_failed_not_forceable',
106
+					__('Registration checkin failed. Please see additional error data.', 'event_espresso')
107
+				)
108
+			);
109
+		}
110
+		$checkin = EEM_Checkin::instance()->get_one(
111
+			array(
112
+				array(
113
+					'REG_ID' => $reg_id,
114
+					'DTT_ID' => $dtt_id,
115
+				),
116
+				'order_by' => array(
117
+					'CHK_timestamp' => 'DESC',
118
+				),
119
+			)
120
+		);
121
+		if (! $checkin instanceof EE_Checkin) {
122
+			return $this->sendResponse(
123
+				new WP_Error(
124
+					'rest_toggle_checkin_error',
125
+					sprintf(
126
+						__(
127
+						// @codingStandardsIgnoreStart
128
+							'Supposedly we created a new checkin object for registration %1$s at datetime %2$s, but we can\'t find it.',
129
+							// @codingStandardsIgnoreEnd
130
+							'event_espresso'
131
+						),
132
+						$reg_id,
133
+						$dtt_id
134
+					)
135
+				)
136
+			);
137
+		}
138
+		$get_request = new WP_REST_Request(
139
+			'GET',
140
+			'/' . EED_Core_Rest_Api::ee_api_namespace . 'v' . $version . '/checkins/' . $checkin->ID()
141
+		);
142
+		$get_request->set_url_params(
143
+			array(
144
+				'id' => $checkin->ID(),
145
+			)
146
+		);
147
+		return Read::handleRequestGetOne($get_request, $version, 'Checkin');
148
+	}
149 149
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             $force = false;
57 57
         }
58 58
         $reg = EEM_Registration::instance()->get_one_by_ID($reg_id);
59
-        if (! $reg instanceof EE_Registration) {
59
+        if ( ! $reg instanceof EE_Registration) {
60 60
             return $this->sendResponse(
61 61
                 new WP_Error(
62 62
                     'rest_registration_toggle_checkin_invalid_id',
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
                 )
72 72
             );
73 73
         }
74
-        if (! EE_Capabilities::instance()->current_user_can('ee_edit_checkin', 'rest_api_checkin_endpoint', $reg_id)) {
74
+        if ( ! EE_Capabilities::instance()->current_user_can('ee_edit_checkin', 'rest_api_checkin_endpoint', $reg_id)) {
75 75
             return $this->sendResponse(
76 76
                 new WP_Error(
77 77
                     'rest_user_cannot_toggle_checkin',
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
         $success = $reg->toggle_checkin_status($dtt_id, ! $force);
87 87
         if ($success === false) {
88 88
             // check if we know they can't check in because they're not approved and we aren't forcing
89
-            if (! $reg->is_approved() && ! $force) {
89
+            if ( ! $reg->is_approved() && ! $force) {
90 90
                 // rely on EE_Error::add_error messages to have been added to give more data about why it failed
91 91
                 return $this->sendResponse(
92 92
                     new WP_Error(
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
                 ),
119 119
             )
120 120
         );
121
-        if (! $checkin instanceof EE_Checkin) {
121
+        if ( ! $checkin instanceof EE_Checkin) {
122 122
             return $this->sendResponse(
123 123
                 new WP_Error(
124 124
                     'rest_toggle_checkin_error',
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
         }
138 138
         $get_request = new WP_REST_Request(
139 139
             'GET',
140
-            '/' . EED_Core_Rest_Api::ee_api_namespace . 'v' . $version . '/checkins/' . $checkin->ID()
140
+            '/'.EED_Core_Rest_Api::ee_api_namespace.'v'.$version.'/checkins/'.$checkin->ID()
141 141
         );
142 142
         $get_request->set_url_params(
143 143
             array(
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlerBaseClasses/JobHandlerFile.php 2 patches
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -16,110 +16,110 @@
 block discarded – undo
16 16
  */
17 17
 abstract class JobHandlerFile extends JobHandler
18 18
 {
19
-    // phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
20
-    const temp_folder_name = 'batch_temp_folder';
19
+	// phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
20
+	const temp_folder_name = 'batch_temp_folder';
21 21
 
22
-    /**
23
-     * @var \EEHI_File
24
-     */
25
-    protected $_file_helper = null;
22
+	/**
23
+	 * @var \EEHI_File
24
+	 */
25
+	protected $_file_helper = null;
26 26
 
27 27
 
28
-    /**
29
-     * JobHandlerFile constructor.
30
-     *
31
-     * @param \EEHI_File|null $file_helper
32
-     */
33
-    public function __construct(\EEHI_File $file_helper = null)
34
-    {
35
-        if (! $file_helper) {
36
-            $this->_file_helper = new \EEH_File();
37
-        }
38
-    }
28
+	/**
29
+	 * JobHandlerFile constructor.
30
+	 *
31
+	 * @param \EEHI_File|null $file_helper
32
+	 */
33
+	public function __construct(\EEHI_File $file_helper = null)
34
+	{
35
+		if (! $file_helper) {
36
+			$this->_file_helper = new \EEH_File();
37
+		}
38
+	}
39 39
 
40
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
41
-    /**
42
-     * Creates a file
43
-     *
44
-     * @param string $job_id
45
-     * @param string $filename
46
-     * @param string $filetype
47
-     * @return string
48
-     * @throws \EventEspressoBatchRequest\Helpers\BatchRequestException
49
-     */
50
-    public function create_file_from_job_with_name($job_id, $filename, $filetype = 'application/ms-excel')
51
-    {
52
-        $filepath = '';
53
-        try {
54
-            $base_folder = $this->get_base_folder();
55
-            $success = $this->_file_helper->ensure_folder_exists_and_is_writable(
56
-                $base_folder . JobHandlerFile::temp_folder_name
57
-            );
58
-            if ($success) {
59
-                $success = $this->_file_helper->ensure_folder_exists_and_is_writable(
60
-                    $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id
61
-                );
62
-            }
63
-            if ($success) {
64
-                $filepath = $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . $filename;
65
-                $success = $this->_file_helper->ensure_file_exists_and_is_writable($filepath);
66
-            }
67
-            // let's add the .htaccess file so safari will open the file properly
68
-            if ($success) {
69
-                $extension = \EEH_File::get_file_extension($filepath);
70
-                \EEH_File::write_to_file(
71
-                    $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . '.htaccess',
72
-                    'AddType ' . $filetype . ' ' . $extension,
73
-                    '.htaccess'
74
-                );
75
-            }
76
-            // those methods normally fail with an exception, but if not, let's do it
77
-            if (! $success) {
78
-                throw new \EE_Error(__('Could not create temporary file, an unknown error occurred', 'event_espresso'));
79
-            }
80
-        } catch (\EE_Error $e) {
81
-            throw new BatchRequestException(
82
-                sprintf(
83
-                    __('Could not create temporary file for job %1$s, because: %2$s ', 'event_espresso'),
84
-                    $job_id,
85
-                    $e->getMessage()
86
-                ),
87
-                500,
88
-                $e
89
-            );
90
-        }
91
-        return $filepath;
92
-    }
40
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
41
+	/**
42
+	 * Creates a file
43
+	 *
44
+	 * @param string $job_id
45
+	 * @param string $filename
46
+	 * @param string $filetype
47
+	 * @return string
48
+	 * @throws \EventEspressoBatchRequest\Helpers\BatchRequestException
49
+	 */
50
+	public function create_file_from_job_with_name($job_id, $filename, $filetype = 'application/ms-excel')
51
+	{
52
+		$filepath = '';
53
+		try {
54
+			$base_folder = $this->get_base_folder();
55
+			$success = $this->_file_helper->ensure_folder_exists_and_is_writable(
56
+				$base_folder . JobHandlerFile::temp_folder_name
57
+			);
58
+			if ($success) {
59
+				$success = $this->_file_helper->ensure_folder_exists_and_is_writable(
60
+					$base_folder . JobHandlerFile::temp_folder_name . DS . $job_id
61
+				);
62
+			}
63
+			if ($success) {
64
+				$filepath = $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . $filename;
65
+				$success = $this->_file_helper->ensure_file_exists_and_is_writable($filepath);
66
+			}
67
+			// let's add the .htaccess file so safari will open the file properly
68
+			if ($success) {
69
+				$extension = \EEH_File::get_file_extension($filepath);
70
+				\EEH_File::write_to_file(
71
+					$base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . '.htaccess',
72
+					'AddType ' . $filetype . ' ' . $extension,
73
+					'.htaccess'
74
+				);
75
+			}
76
+			// those methods normally fail with an exception, but if not, let's do it
77
+			if (! $success) {
78
+				throw new \EE_Error(__('Could not create temporary file, an unknown error occurred', 'event_espresso'));
79
+			}
80
+		} catch (\EE_Error $e) {
81
+			throw new BatchRequestException(
82
+				sprintf(
83
+					__('Could not create temporary file for job %1$s, because: %2$s ', 'event_espresso'),
84
+					$job_id,
85
+					$e->getMessage()
86
+				),
87
+				500,
88
+				$e
89
+			);
90
+		}
91
+		return $filepath;
92
+	}
93 93
 
94
-    /**
95
-     * Gets the URL to download the file
96
-     *
97
-     * @param string $filepath
98
-     * @return string url to file
99
-     */
100
-    public function get_url_to_file($filepath)
101
-    {
102
-        return str_replace($this->get_base_folder(), $this->get_base_url(), $filepath);
103
-    }
94
+	/**
95
+	 * Gets the URL to download the file
96
+	 *
97
+	 * @param string $filepath
98
+	 * @return string url to file
99
+	 */
100
+	public function get_url_to_file($filepath)
101
+	{
102
+		return str_replace($this->get_base_folder(), $this->get_base_url(), $filepath);
103
+	}
104 104
 
105
-    /**
106
-     * Gets the folder which will contain the "batch_temp_folder"
107
-     *
108
-     * @return string
109
-     */
110
-    public function get_base_folder()
111
-    {
112
-        return apply_filters(
113
-            'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_folder',
114
-            EVENT_ESPRESSO_UPLOAD_DIR
115
-        );
116
-    }
105
+	/**
106
+	 * Gets the folder which will contain the "batch_temp_folder"
107
+	 *
108
+	 * @return string
109
+	 */
110
+	public function get_base_folder()
111
+	{
112
+		return apply_filters(
113
+			'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_folder',
114
+			EVENT_ESPRESSO_UPLOAD_DIR
115
+		);
116
+	}
117 117
 
118
-    public function get_base_url()
119
-    {
120
-        return apply_filters(
121
-            'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_url',
122
-            EVENT_ESPRESSO_UPLOAD_URL
123
-        );
124
-    }
118
+	public function get_base_url()
119
+	{
120
+		return apply_filters(
121
+			'FHEE__EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile__get_base_url',
122
+			EVENT_ESPRESSO_UPLOAD_URL
123
+		);
124
+	}
125 125
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function __construct(\EEHI_File $file_helper = null)
34 34
     {
35
-        if (! $file_helper) {
35
+        if ( ! $file_helper) {
36 36
             $this->_file_helper = new \EEH_File();
37 37
         }
38 38
     }
@@ -53,28 +53,28 @@  discard block
 block discarded – undo
53 53
         try {
54 54
             $base_folder = $this->get_base_folder();
55 55
             $success = $this->_file_helper->ensure_folder_exists_and_is_writable(
56
-                $base_folder . JobHandlerFile::temp_folder_name
56
+                $base_folder.JobHandlerFile::temp_folder_name
57 57
             );
58 58
             if ($success) {
59 59
                 $success = $this->_file_helper->ensure_folder_exists_and_is_writable(
60
-                    $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id
60
+                    $base_folder.JobHandlerFile::temp_folder_name.DS.$job_id
61 61
                 );
62 62
             }
63 63
             if ($success) {
64
-                $filepath = $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . $filename;
64
+                $filepath = $base_folder.JobHandlerFile::temp_folder_name.DS.$job_id.DS.$filename;
65 65
                 $success = $this->_file_helper->ensure_file_exists_and_is_writable($filepath);
66 66
             }
67 67
             // let's add the .htaccess file so safari will open the file properly
68 68
             if ($success) {
69 69
                 $extension = \EEH_File::get_file_extension($filepath);
70 70
                 \EEH_File::write_to_file(
71
-                    $base_folder . JobHandlerFile::temp_folder_name . DS . $job_id . DS . '.htaccess',
72
-                    'AddType ' . $filetype . ' ' . $extension,
71
+                    $base_folder.JobHandlerFile::temp_folder_name.DS.$job_id.DS.'.htaccess',
72
+                    'AddType '.$filetype.' '.$extension,
73 73
                     '.htaccess'
74 74
                 );
75 75
             }
76 76
             // those methods normally fail with an exception, but if not, let's do it
77
-            if (! $success) {
77
+            if ( ! $success) {
78 78
                 throw new \EE_Error(__('Could not create temporary file, an unknown error occurred', 'event_espresso'));
79 79
             }
80 80
         } catch (\EE_Error $e) {
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlerBaseClasses/JobHandler.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -13,5 +13,5 @@
 block discarded – undo
13 13
  */
14 14
 abstract class JobHandler implements JobHandlerInterface
15 15
 {
16
-    // so far no common methods or properties
16
+	// so far no common methods or properties
17 17
 }
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/BatchRequestException.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -14,5 +14,5 @@
 block discarded – undo
14 14
  */
15 15
 class BatchRequestException extends \Exception
16 16
 {
17
-    // so far the same as exception
17
+	// so far the same as exception
18 18
 }
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/JobParameters.php 2 patches
Indentation   +391 added lines, -391 removed lines patch added patch discarded remove patch
@@ -14,395 +14,395 @@
 block discarded – undo
14 14
  */
15 15
 class JobParameters
16 16
 {
17
-    // phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
18
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
19
-    /**
20
-     * status indicating the job should continue
21
-     */
22
-    const status_continue = 'continue';
23
-
24
-    /**
25
-     * status indicated the job has been completed successfully and should be cleaned up next
26
-     */
27
-    const status_complete = 'complete';
28
-
29
-    /**
30
-     * status indicating there was an error and the job should be cleaned up
31
-     */
32
-    const status_error = 'error';
33
-
34
-    /**
35
-     * status indicating the job has been cleaned up, and so this is probably the last
36
-     * time you'll see this job
37
-     */
38
-    const status_cleaned_up = 'cleaned_up';
39
-
40
-    const wp_option_prefix = 'ee_job_parameters_';
41
-
42
-
43
-    /**
44
-     * String uniquely identifying the job
45
-     *
46
-     * @var string
47
-     */
48
-    protected $_job_id;
49
-
50
-    /**
51
-     * @var string
52
-     */
53
-    protected $_classname;
54
-
55
-    /**
56
-     * @var array
57
-     */
58
-    protected $_request_data;
59
-
60
-    /**
61
-     * Array of any extra data we want to remember about this request, that
62
-     * wasn't necessarily past in with the request data
63
-     *
64
-     * @var array
65
-     */
66
-    protected $_extra_data;
67
-
68
-    /**
69
-     * Estimate of how many units HAVE been processed
70
-     *
71
-     * @var int
72
-     */
73
-    protected $_units_processed = 0;
74
-
75
-    /**
76
-     * @var string
77
-     */
78
-    protected $_status;
79
-
80
-    /**
81
-     * The size of the total job in whatever units you want.
82
-     * If you can't provide an estimate leave as 0.
83
-     * Once _units_processed equals _job_size, we should be done
84
-     *
85
-     * @var int
86
-     */
87
-    protected $_job_size = 0;
88
-
89
-
90
-    /**
91
-     * @param string $job_id
92
-     * @param string $classname
93
-     * @param array  $request_data
94
-     * @param array  $extra_data
95
-     */
96
-    public function __construct($job_id, $classname, $request_data, $extra_data = array())
97
-    {
98
-        $this->set_job_id($job_id);
99
-        $this->set_classname($classname);
100
-        $this->set_request_data($request_data);
101
-        $this->set_extra_data($extra_data);
102
-        $this->set_status(JobParameters::status_continue);
103
-    }
104
-
105
-
106
-    /**
107
-     * Returns the array of strings of valid stati
108
-     *
109
-     * @return array
110
-     */
111
-    public static function valid_stati()
112
-    {
113
-        return array(
114
-            JobParameters::status_complete,
115
-            JobParameters::status_continue,
116
-            JobParameters::status_error,
117
-            JobParameters::status_cleaned_up,
118
-        );
119
-    }
120
-
121
-
122
-    /**
123
-     * Saves this option to the database (wordpress options table)
124
-     *
125
-     * @param boolean $first
126
-     * @return boolean success
127
-     */
128
-    public function save($first = false)
129
-    {
130
-        $object_vars = get_object_vars($this);
131
-        if ($first) {
132
-            return add_option($this->option_name(), $object_vars, null, 'no');
133
-        } else {
134
-            return update_option($this->option_name(), $object_vars);
135
-        }
136
-    }
137
-
138
-
139
-    /**
140
-     * Deletes the job from teh database, although this object is still usable
141
-     * for the rest of the request
142
-     *
143
-     * @return boolean
144
-     */
145
-    public function delete()
146
-    {
147
-        return delete_option($this->option_name());
148
-    }
149
-
150
-
151
-    /**
152
-     * Loads the specified job from the database
153
-     *
154
-     * @param string $job_id
155
-     * @return JobParameters
156
-     * @throws BatchRequestException
157
-     */
158
-    public static function load($job_id)
159
-    {
160
-        $job_parameter_vars = get_option(JobParameters::wp_option_prefix . $job_id);
161
-        if (! is_array($job_parameter_vars) ||
162
-            ! isset($job_parameter_vars['_classname']) ||
163
-            ! isset($job_parameter_vars['_request_data'])
164
-        ) {
165
-            throw new BatchRequestException(
166
-                sprintf(
167
-                    __(
168
-                        'Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s',
169
-                        'event_espresso'
170
-                    ),
171
-                    $job_id,
172
-                    get_option(JobParameters::wp_option_prefix . $job_id)
173
-                )
174
-            );
175
-        }
176
-        $job_parameters = new JobParameters(
177
-            $job_id,
178
-            $job_parameter_vars['_classname'],
179
-            $job_parameter_vars['_request_data']
180
-        );
181
-        foreach ($job_parameter_vars as $key => $value) {
182
-            $job_parameters->{$key} = $value;
183
-        }
184
-        return $job_parameters;
185
-    }
186
-
187
-
188
-    /**
189
-     * Gets the job's unique string
190
-     *
191
-     * @return string
192
-     */
193
-    public function job_id()
194
-    {
195
-        return $this->_job_id;
196
-    }
197
-
198
-
199
-    /**
200
-     * Gets the classname that should run this job
201
-     *
202
-     * @return string
203
-     */
204
-    public function classname()
205
-    {
206
-        return $this->_classname;
207
-    }
208
-
209
-
210
-    /**
211
-     * Gets the original array of $_REQUEST data for this job
212
-     *
213
-     * @return array
214
-     */
215
-    public function request_data()
216
-    {
217
-        return $this->_request_data;
218
-    }
219
-
220
-
221
-    /**
222
-     * Gets a single item from the request data
223
-     *
224
-     * @param string       $key
225
-     * @param string|array $default
226
-     * @return string|array
227
-     */
228
-    public function request_datum($key, $default = '')
229
-    {
230
-        if (isset($this->_request_data[$key])) {
231
-            return $this->_request_data[$key];
232
-        } else {
233
-            return $default;
234
-        }
235
-    }
236
-
237
-
238
-    /**
239
-     * Gets a single item from the extra data
240
-     *
241
-     * @param string       $key
242
-     * @param string|array $default
243
-     * @return string|array
244
-     */
245
-    public function extra_datum($key, $default = '')
246
-    {
247
-        if (isset($this->_extra_data[$key])) {
248
-            return $this->_extra_data[$key];
249
-        } else {
250
-            return $default;
251
-        }
252
-    }
253
-
254
-
255
-    /**
256
-     * Adds an extra piece of extra data that we're going to want later during the job
257
-     *
258
-     * @param string                $key
259
-     * @param string|int|array|null $value almost any extra data you want to store
260
-     */
261
-    public function add_extra_data($key, $value)
262
-    {
263
-        $this->_extra_data[$key] = $value;
264
-    }
265
-
266
-
267
-    /**
268
-     * Array of any extra data we want to store
269
-     *
270
-     * @return array
271
-     */
272
-    public function extra_data()
273
-    {
274
-        return $this->_extra_data;
275
-    }
276
-
277
-
278
-    /**
279
-     * Returns the job size, in whatever units you want
280
-     *
281
-     * @return int
282
-     */
283
-    public function job_size()
284
-    {
285
-        return $this->_job_size;
286
-    }
287
-
288
-
289
-    /**
290
-     * Sets the job size. You decide what units to use
291
-     *
292
-     * @param int $size
293
-     */
294
-    public function set_job_size($size)
295
-    {
296
-        $this->_job_size = $size;
297
-    }
298
-
299
-
300
-    /**
301
-     * The number of "units" processed, in the same units as the "job size"
302
-     *
303
-     * @return int
304
-     */
305
-    public function units_processed()
306
-    {
307
-        return $this->_units_processed;
308
-    }
309
-
310
-
311
-    /**
312
-     * Marks more units as processed
313
-     *
314
-     * @param int $newly_processed
315
-     * @return int updated units processed
316
-     */
317
-    public function mark_processed($newly_processed)
318
-    {
319
-        $this->_units_processed += $newly_processed;
320
-        return $this->_units_processed;
321
-    }
322
-
323
-
324
-    /**
325
-     * Sets the total count of units processed. You might prefer to use mark_processed
326
-     *
327
-     * @param int $total_units_processed
328
-     */
329
-    public function set_units_processed($total_units_processed)
330
-    {
331
-        $this->_units_processed = $total_units_processed;
332
-    }
333
-
334
-
335
-    /**
336
-     * Sets the job's ID
337
-     *
338
-     * @param string $job_id
339
-     */
340
-    public function set_job_id($job_id)
341
-    {
342
-        $this->_job_id = $job_id;
343
-    }
344
-
345
-
346
-    /**
347
-     * sets the classname
348
-     *
349
-     * @param string $classname
350
-     */
351
-    public function set_classname($classname)
352
-    {
353
-        $this->_classname = $classname;
354
-    }
355
-
356
-
357
-    /**
358
-     * Sets the request data
359
-     *
360
-     * @param array $request_data
361
-     */
362
-    public function set_request_data($request_data)
363
-    {
364
-        $this->_request_data = $request_data;
365
-    }
366
-
367
-
368
-    /**
369
-     * Sets the array of extra data we want to store on this request
370
-     *
371
-     * @param array $extra_data
372
-     */
373
-    public function set_extra_data($extra_data)
374
-    {
375
-        $this->_extra_data = $extra_data;
376
-    }
377
-
378
-
379
-    /**
380
-     * Gets the name of the wordpress option that should store these job parameters
381
-     *
382
-     * @return string
383
-     */
384
-    public function option_name()
385
-    {
386
-        return JobParameters::wp_option_prefix . $this->job_id();
387
-    }
388
-
389
-
390
-    /**
391
-     * Gets the job\s current status. One of JobParameters::valid_stati();
392
-     *
393
-     * @return string
394
-     */
395
-    public function status()
396
-    {
397
-        return $this->_status;
398
-    }
399
-
400
-
401
-    /**
402
-     * @param string $status on eof JobParameters::valid_stati()
403
-     */
404
-    public function set_status($status)
405
-    {
406
-        $this->_status = $status;
407
-    }
17
+	// phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
18
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
19
+	/**
20
+	 * status indicating the job should continue
21
+	 */
22
+	const status_continue = 'continue';
23
+
24
+	/**
25
+	 * status indicated the job has been completed successfully and should be cleaned up next
26
+	 */
27
+	const status_complete = 'complete';
28
+
29
+	/**
30
+	 * status indicating there was an error and the job should be cleaned up
31
+	 */
32
+	const status_error = 'error';
33
+
34
+	/**
35
+	 * status indicating the job has been cleaned up, and so this is probably the last
36
+	 * time you'll see this job
37
+	 */
38
+	const status_cleaned_up = 'cleaned_up';
39
+
40
+	const wp_option_prefix = 'ee_job_parameters_';
41
+
42
+
43
+	/**
44
+	 * String uniquely identifying the job
45
+	 *
46
+	 * @var string
47
+	 */
48
+	protected $_job_id;
49
+
50
+	/**
51
+	 * @var string
52
+	 */
53
+	protected $_classname;
54
+
55
+	/**
56
+	 * @var array
57
+	 */
58
+	protected $_request_data;
59
+
60
+	/**
61
+	 * Array of any extra data we want to remember about this request, that
62
+	 * wasn't necessarily past in with the request data
63
+	 *
64
+	 * @var array
65
+	 */
66
+	protected $_extra_data;
67
+
68
+	/**
69
+	 * Estimate of how many units HAVE been processed
70
+	 *
71
+	 * @var int
72
+	 */
73
+	protected $_units_processed = 0;
74
+
75
+	/**
76
+	 * @var string
77
+	 */
78
+	protected $_status;
79
+
80
+	/**
81
+	 * The size of the total job in whatever units you want.
82
+	 * If you can't provide an estimate leave as 0.
83
+	 * Once _units_processed equals _job_size, we should be done
84
+	 *
85
+	 * @var int
86
+	 */
87
+	protected $_job_size = 0;
88
+
89
+
90
+	/**
91
+	 * @param string $job_id
92
+	 * @param string $classname
93
+	 * @param array  $request_data
94
+	 * @param array  $extra_data
95
+	 */
96
+	public function __construct($job_id, $classname, $request_data, $extra_data = array())
97
+	{
98
+		$this->set_job_id($job_id);
99
+		$this->set_classname($classname);
100
+		$this->set_request_data($request_data);
101
+		$this->set_extra_data($extra_data);
102
+		$this->set_status(JobParameters::status_continue);
103
+	}
104
+
105
+
106
+	/**
107
+	 * Returns the array of strings of valid stati
108
+	 *
109
+	 * @return array
110
+	 */
111
+	public static function valid_stati()
112
+	{
113
+		return array(
114
+			JobParameters::status_complete,
115
+			JobParameters::status_continue,
116
+			JobParameters::status_error,
117
+			JobParameters::status_cleaned_up,
118
+		);
119
+	}
120
+
121
+
122
+	/**
123
+	 * Saves this option to the database (wordpress options table)
124
+	 *
125
+	 * @param boolean $first
126
+	 * @return boolean success
127
+	 */
128
+	public function save($first = false)
129
+	{
130
+		$object_vars = get_object_vars($this);
131
+		if ($first) {
132
+			return add_option($this->option_name(), $object_vars, null, 'no');
133
+		} else {
134
+			return update_option($this->option_name(), $object_vars);
135
+		}
136
+	}
137
+
138
+
139
+	/**
140
+	 * Deletes the job from teh database, although this object is still usable
141
+	 * for the rest of the request
142
+	 *
143
+	 * @return boolean
144
+	 */
145
+	public function delete()
146
+	{
147
+		return delete_option($this->option_name());
148
+	}
149
+
150
+
151
+	/**
152
+	 * Loads the specified job from the database
153
+	 *
154
+	 * @param string $job_id
155
+	 * @return JobParameters
156
+	 * @throws BatchRequestException
157
+	 */
158
+	public static function load($job_id)
159
+	{
160
+		$job_parameter_vars = get_option(JobParameters::wp_option_prefix . $job_id);
161
+		if (! is_array($job_parameter_vars) ||
162
+			! isset($job_parameter_vars['_classname']) ||
163
+			! isset($job_parameter_vars['_request_data'])
164
+		) {
165
+			throw new BatchRequestException(
166
+				sprintf(
167
+					__(
168
+						'Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s',
169
+						'event_espresso'
170
+					),
171
+					$job_id,
172
+					get_option(JobParameters::wp_option_prefix . $job_id)
173
+				)
174
+			);
175
+		}
176
+		$job_parameters = new JobParameters(
177
+			$job_id,
178
+			$job_parameter_vars['_classname'],
179
+			$job_parameter_vars['_request_data']
180
+		);
181
+		foreach ($job_parameter_vars as $key => $value) {
182
+			$job_parameters->{$key} = $value;
183
+		}
184
+		return $job_parameters;
185
+	}
186
+
187
+
188
+	/**
189
+	 * Gets the job's unique string
190
+	 *
191
+	 * @return string
192
+	 */
193
+	public function job_id()
194
+	{
195
+		return $this->_job_id;
196
+	}
197
+
198
+
199
+	/**
200
+	 * Gets the classname that should run this job
201
+	 *
202
+	 * @return string
203
+	 */
204
+	public function classname()
205
+	{
206
+		return $this->_classname;
207
+	}
208
+
209
+
210
+	/**
211
+	 * Gets the original array of $_REQUEST data for this job
212
+	 *
213
+	 * @return array
214
+	 */
215
+	public function request_data()
216
+	{
217
+		return $this->_request_data;
218
+	}
219
+
220
+
221
+	/**
222
+	 * Gets a single item from the request data
223
+	 *
224
+	 * @param string       $key
225
+	 * @param string|array $default
226
+	 * @return string|array
227
+	 */
228
+	public function request_datum($key, $default = '')
229
+	{
230
+		if (isset($this->_request_data[$key])) {
231
+			return $this->_request_data[$key];
232
+		} else {
233
+			return $default;
234
+		}
235
+	}
236
+
237
+
238
+	/**
239
+	 * Gets a single item from the extra data
240
+	 *
241
+	 * @param string       $key
242
+	 * @param string|array $default
243
+	 * @return string|array
244
+	 */
245
+	public function extra_datum($key, $default = '')
246
+	{
247
+		if (isset($this->_extra_data[$key])) {
248
+			return $this->_extra_data[$key];
249
+		} else {
250
+			return $default;
251
+		}
252
+	}
253
+
254
+
255
+	/**
256
+	 * Adds an extra piece of extra data that we're going to want later during the job
257
+	 *
258
+	 * @param string                $key
259
+	 * @param string|int|array|null $value almost any extra data you want to store
260
+	 */
261
+	public function add_extra_data($key, $value)
262
+	{
263
+		$this->_extra_data[$key] = $value;
264
+	}
265
+
266
+
267
+	/**
268
+	 * Array of any extra data we want to store
269
+	 *
270
+	 * @return array
271
+	 */
272
+	public function extra_data()
273
+	{
274
+		return $this->_extra_data;
275
+	}
276
+
277
+
278
+	/**
279
+	 * Returns the job size, in whatever units you want
280
+	 *
281
+	 * @return int
282
+	 */
283
+	public function job_size()
284
+	{
285
+		return $this->_job_size;
286
+	}
287
+
288
+
289
+	/**
290
+	 * Sets the job size. You decide what units to use
291
+	 *
292
+	 * @param int $size
293
+	 */
294
+	public function set_job_size($size)
295
+	{
296
+		$this->_job_size = $size;
297
+	}
298
+
299
+
300
+	/**
301
+	 * The number of "units" processed, in the same units as the "job size"
302
+	 *
303
+	 * @return int
304
+	 */
305
+	public function units_processed()
306
+	{
307
+		return $this->_units_processed;
308
+	}
309
+
310
+
311
+	/**
312
+	 * Marks more units as processed
313
+	 *
314
+	 * @param int $newly_processed
315
+	 * @return int updated units processed
316
+	 */
317
+	public function mark_processed($newly_processed)
318
+	{
319
+		$this->_units_processed += $newly_processed;
320
+		return $this->_units_processed;
321
+	}
322
+
323
+
324
+	/**
325
+	 * Sets the total count of units processed. You might prefer to use mark_processed
326
+	 *
327
+	 * @param int $total_units_processed
328
+	 */
329
+	public function set_units_processed($total_units_processed)
330
+	{
331
+		$this->_units_processed = $total_units_processed;
332
+	}
333
+
334
+
335
+	/**
336
+	 * Sets the job's ID
337
+	 *
338
+	 * @param string $job_id
339
+	 */
340
+	public function set_job_id($job_id)
341
+	{
342
+		$this->_job_id = $job_id;
343
+	}
344
+
345
+
346
+	/**
347
+	 * sets the classname
348
+	 *
349
+	 * @param string $classname
350
+	 */
351
+	public function set_classname($classname)
352
+	{
353
+		$this->_classname = $classname;
354
+	}
355
+
356
+
357
+	/**
358
+	 * Sets the request data
359
+	 *
360
+	 * @param array $request_data
361
+	 */
362
+	public function set_request_data($request_data)
363
+	{
364
+		$this->_request_data = $request_data;
365
+	}
366
+
367
+
368
+	/**
369
+	 * Sets the array of extra data we want to store on this request
370
+	 *
371
+	 * @param array $extra_data
372
+	 */
373
+	public function set_extra_data($extra_data)
374
+	{
375
+		$this->_extra_data = $extra_data;
376
+	}
377
+
378
+
379
+	/**
380
+	 * Gets the name of the wordpress option that should store these job parameters
381
+	 *
382
+	 * @return string
383
+	 */
384
+	public function option_name()
385
+	{
386
+		return JobParameters::wp_option_prefix . $this->job_id();
387
+	}
388
+
389
+
390
+	/**
391
+	 * Gets the job\s current status. One of JobParameters::valid_stati();
392
+	 *
393
+	 * @return string
394
+	 */
395
+	public function status()
396
+	{
397
+		return $this->_status;
398
+	}
399
+
400
+
401
+	/**
402
+	 * @param string $status on eof JobParameters::valid_stati()
403
+	 */
404
+	public function set_status($status)
405
+	{
406
+		$this->_status = $status;
407
+	}
408 408
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -157,8 +157,8 @@  discard block
 block discarded – undo
157 157
      */
158 158
     public static function load($job_id)
159 159
     {
160
-        $job_parameter_vars = get_option(JobParameters::wp_option_prefix . $job_id);
161
-        if (! is_array($job_parameter_vars) ||
160
+        $job_parameter_vars = get_option(JobParameters::wp_option_prefix.$job_id);
161
+        if ( ! is_array($job_parameter_vars) ||
162 162
             ! isset($job_parameter_vars['_classname']) ||
163 163
             ! isset($job_parameter_vars['_request_data'])
164 164
         ) {
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
                         'event_espresso'
170 170
                     ),
171 171
                     $job_id,
172
-                    get_option(JobParameters::wp_option_prefix . $job_id)
172
+                    get_option(JobParameters::wp_option_prefix.$job_id)
173 173
                 )
174 174
             );
175 175
         }
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
      */
384 384
     public function option_name()
385 385
     {
386
-        return JobParameters::wp_option_prefix . $this->job_id();
386
+        return JobParameters::wp_option_prefix.$this->job_id();
387 387
     }
388 388
 
389 389
 
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/JobStepResponse.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -14,97 +14,97 @@
 block discarded – undo
14 14
 class JobStepResponse
15 15
 {
16 16
 
17
-    /**
18
-     * Description fo what happened during this step
19
-     *
20
-     * @var string
21
-     */
22
-    protected $_update_text;
17
+	/**
18
+	 * Description fo what happened during this step
19
+	 *
20
+	 * @var string
21
+	 */
22
+	protected $_update_text;
23 23
 
24
-    /**
25
-     * @var JobParameters
26
-     */
27
-    protected $_job_parameters;
24
+	/**
25
+	 * @var JobParameters
26
+	 */
27
+	protected $_job_parameters;
28 28
 
29
-    /**
30
-     * Extra data to include as part of the response.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_extra_data = array();
29
+	/**
30
+	 * Extra data to include as part of the response.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_extra_data = array();
35 35
 
36
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
37
-    /**
38
-     * @param \EventEspressoBatchRequest\Helpers\JobParameters $job_parameters
39
-     * @param string                                           $update_text
40
-     * @param array                                            $extra_data
41
-     */
42
-    public function __construct(JobParameters $job_parameters, $update_text, $extra_data = array())
43
-    {
44
-        $this->_job_parameters = $job_parameters;
45
-        $this->_update_text = $update_text;
46
-        $this->_extra_data = (array)$extra_data;
47
-    }
36
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
37
+	/**
38
+	 * @param \EventEspressoBatchRequest\Helpers\JobParameters $job_parameters
39
+	 * @param string                                           $update_text
40
+	 * @param array                                            $extra_data
41
+	 */
42
+	public function __construct(JobParameters $job_parameters, $update_text, $extra_data = array())
43
+	{
44
+		$this->_job_parameters = $job_parameters;
45
+		$this->_update_text = $update_text;
46
+		$this->_extra_data = (array)$extra_data;
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * @return JobParameters
52
-     */
53
-    public function job_parameters()
54
-    {
55
-        return $this->_job_parameters;
56
-    }
50
+	/**
51
+	 * @return JobParameters
52
+	 */
53
+	public function job_parameters()
54
+	{
55
+		return $this->_job_parameters;
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * Gets the update_text of what happened in this job during the current step
61
-     *
62
-     * @return string
63
-     */
64
-    public function update_text()
65
-    {
66
-        return $this->_update_text;
67
-    }
59
+	/**
60
+	 * Gets the update_text of what happened in this job during the current step
61
+	 *
62
+	 * @return string
63
+	 */
64
+	public function update_text()
65
+	{
66
+		return $this->_update_text;
67
+	}
68 68
 
69 69
 
70
-    /**
71
-     * Returns any extra data we may want to include with this response
72
-     *
73
-     * @return array
74
-     */
75
-    public function extra_data()
76
-    {
77
-        return $this->_extra_data;
78
-    }
70
+	/**
71
+	 * Returns any extra data we may want to include with this response
72
+	 *
73
+	 * @return array
74
+	 */
75
+	public function extra_data()
76
+	{
77
+		return $this->_extra_data;
78
+	}
79 79
 
80 80
 
81
-    /**
82
-     * Converts this response into an array that can be easily serialized.
83
-     * This is most useful for serializing or json encoding
84
-     *
85
-     * @return array {
86
-     * @type string $status          , one of JobParameters::valid_stati()
87
-     * @type int    $units_processed count of units processed
88
-     * @type int    $job_size        total number of units TO process
89
-     * @type string $job_id          unique string identifying the job
90
-     * @type string $update_text     string describing what happened during this step
91
-     * } and any other items from $this->extra_data()
92
-     */
93
-    public function to_array()
94
-    {
95
-        return apply_filters(
96
-            'FHEE__EventEspressoBatchRequest\Helpers\JobStepResponse__to_array__return',
97
-            array_merge(
98
-                $this->extra_data(),
99
-                array(
100
-                    'status'          => $this->job_parameters()->status(),
101
-                    'units_processed' => $this->job_parameters()->units_processed(),
102
-                    'job_size'        => $this->job_parameters()->job_size(),
103
-                    'job_id'          => $this->job_parameters()->job_id(),
104
-                    'update_text'     => $this->update_text(),
105
-                )
106
-            ),
107
-            $this
108
-        );
109
-    }
81
+	/**
82
+	 * Converts this response into an array that can be easily serialized.
83
+	 * This is most useful for serializing or json encoding
84
+	 *
85
+	 * @return array {
86
+	 * @type string $status          , one of JobParameters::valid_stati()
87
+	 * @type int    $units_processed count of units processed
88
+	 * @type int    $job_size        total number of units TO process
89
+	 * @type string $job_id          unique string identifying the job
90
+	 * @type string $update_text     string describing what happened during this step
91
+	 * } and any other items from $this->extra_data()
92
+	 */
93
+	public function to_array()
94
+	{
95
+		return apply_filters(
96
+			'FHEE__EventEspressoBatchRequest\Helpers\JobStepResponse__to_array__return',
97
+			array_merge(
98
+				$this->extra_data(),
99
+				array(
100
+					'status'          => $this->job_parameters()->status(),
101
+					'units_processed' => $this->job_parameters()->units_processed(),
102
+					'job_size'        => $this->job_parameters()->job_size(),
103
+					'job_id'          => $this->job_parameters()->job_id(),
104
+					'update_text'     => $this->update_text(),
105
+				)
106
+			),
107
+			$this
108
+		);
109
+	}
110 110
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@
 block discarded – undo
43 43
     {
44 44
         $this->_job_parameters = $job_parameters;
45 45
         $this->_update_text = $update_text;
46
-        $this->_extra_data = (array)$extra_data;
46
+        $this->_extra_data = (array) $extra_data;
47 47
     }
48 48
 
49 49
 
Please login to merge, or discard this patch.
core/libraries/batch/BatchRequestProcessor.php 2 patches
Indentation   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -24,201 +24,201 @@
 block discarded – undo
24 24
 class BatchRequestProcessor
25 25
 {
26 26
 
27
-    /**
28
-     * Current job's ID (if assigned)
29
-     *
30
-     * @var string|null
31
-     */
32
-    protected $_job_id;
27
+	/**
28
+	 * Current job's ID (if assigned)
29
+	 *
30
+	 * @var string|null
31
+	 */
32
+	protected $_job_id;
33 33
 
34
-    /**
35
-     * Current job's parameters
36
-     *
37
-     * @var JobParameters|null
38
-     */
39
-    protected $_job_parameters;
34
+	/**
35
+	 * Current job's parameters
36
+	 *
37
+	 * @var JobParameters|null
38
+	 */
39
+	protected $_job_parameters;
40 40
 
41
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
42
-    /**
43
-     * Creates a job for the specified batch handler class (which should be autoloaded)
44
-     * and the specified request data
45
-     *
46
-     * @param string $batch_job_handler_class of an auto-loaded class implementing JobHandlerInterface
47
-     * @param array  $request_data            to be used by the batch job handler
48
-     * @return JobStepResponse
49
-     */
50
-    public function create_job($batch_job_handler_class, $request_data)
51
-    {
52
-        try {
53
-            $this->_job_id = wp_generate_password(15, false);
54
-            $obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
55
-            $this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
56
-            $response = $obj->create_job($this->_job_parameters);
57
-            if (! $response instanceof JobStepResponse) {
58
-                throw new BatchRequestException(
59
-                    sprintf(
60
-                        __(
61
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when create_job was called with %1$s. It needs to return one or throw an Exception',
62
-                            'event_espresso'
63
-                        ),
64
-                        wp_json_encode($request_data)
65
-                    )
66
-                );
67
-            }
68
-            $success = $this->_job_parameters->save(true);
69
-            if (! $success) {
70
-                throw new BatchRequestException(
71
-                    sprintf(
72
-                        __(
73
-                            'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
74
-                            'event_espresso'
75
-                        ),
76
-                        $this->_job_id,
77
-                        wp_json_encode($request_data)
78
-                    )
79
-                );
80
-            }
81
-        } catch (\Exception $e) {
82
-            $response = $this->_get_error_response($e, 'create_job');
83
-        }
84
-        return $response;
85
-    }
41
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
42
+	/**
43
+	 * Creates a job for the specified batch handler class (which should be autoloaded)
44
+	 * and the specified request data
45
+	 *
46
+	 * @param string $batch_job_handler_class of an auto-loaded class implementing JobHandlerInterface
47
+	 * @param array  $request_data            to be used by the batch job handler
48
+	 * @return JobStepResponse
49
+	 */
50
+	public function create_job($batch_job_handler_class, $request_data)
51
+	{
52
+		try {
53
+			$this->_job_id = wp_generate_password(15, false);
54
+			$obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
55
+			$this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
56
+			$response = $obj->create_job($this->_job_parameters);
57
+			if (! $response instanceof JobStepResponse) {
58
+				throw new BatchRequestException(
59
+					sprintf(
60
+						__(
61
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when create_job was called with %1$s. It needs to return one or throw an Exception',
62
+							'event_espresso'
63
+						),
64
+						wp_json_encode($request_data)
65
+					)
66
+				);
67
+			}
68
+			$success = $this->_job_parameters->save(true);
69
+			if (! $success) {
70
+				throw new BatchRequestException(
71
+					sprintf(
72
+						__(
73
+							'Could not save job %1$s to the Wordpress Options table. These were the arguments used: %2$s',
74
+							'event_espresso'
75
+						),
76
+						$this->_job_id,
77
+						wp_json_encode($request_data)
78
+					)
79
+				);
80
+			}
81
+		} catch (\Exception $e) {
82
+			$response = $this->_get_error_response($e, 'create_job');
83
+		}
84
+		return $response;
85
+	}
86 86
 
87 87
 
88
-    /**
89
-     * Retrieves the job's arguments
90
-     *
91
-     * @param string $job_id
92
-     * @param int    $batch_size
93
-     * @return JobStepResponse
94
-     */
95
-    public function continue_job($job_id, $batch_size = 50)
96
-    {
97
-        try {
98
-            $this->_job_id = $job_id;
99
-            $batch_size = defined('EE_BATCHRUNNER_BATCH_SIZE') ? EE_BATCHRUNNER_BATCH_SIZE : $batch_size;
100
-            // get the corresponding WordPress option for the job
101
-            $this->_job_parameters = JobParameters::load($this->_job_id);
102
-            $handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
103
-            // continue it
104
-            $response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
105
-            if (! $response instanceof JobStepResponse) {
106
-                throw new BatchRequestException(
107
-                    sprintf(
108
-                        __(
109
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when continue_job was called with job %1$s. It needs to return one or throw an Exception',
110
-                            'event_espresso'
111
-                        ),
112
-                        $this->_job_id
113
-                    )
114
-                );
115
-            }
116
-            $this->_job_parameters->save();
117
-        } catch (\Exception $e) {
118
-            $response = $this->_get_error_response($e, 'continue_job');
119
-        }
120
-        return $response;
121
-    }
88
+	/**
89
+	 * Retrieves the job's arguments
90
+	 *
91
+	 * @param string $job_id
92
+	 * @param int    $batch_size
93
+	 * @return JobStepResponse
94
+	 */
95
+	public function continue_job($job_id, $batch_size = 50)
96
+	{
97
+		try {
98
+			$this->_job_id = $job_id;
99
+			$batch_size = defined('EE_BATCHRUNNER_BATCH_SIZE') ? EE_BATCHRUNNER_BATCH_SIZE : $batch_size;
100
+			// get the corresponding WordPress option for the job
101
+			$this->_job_parameters = JobParameters::load($this->_job_id);
102
+			$handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
103
+			// continue it
104
+			$response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
105
+			if (! $response instanceof JobStepResponse) {
106
+				throw new BatchRequestException(
107
+					sprintf(
108
+						__(
109
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when continue_job was called with job %1$s. It needs to return one or throw an Exception',
110
+							'event_espresso'
111
+						),
112
+						$this->_job_id
113
+					)
114
+				);
115
+			}
116
+			$this->_job_parameters->save();
117
+		} catch (\Exception $e) {
118
+			$response = $this->_get_error_response($e, 'continue_job');
119
+		}
120
+		return $response;
121
+	}
122 122
 
123 123
 
124
-    /**
125
-     * Instantiates an object of type $classname, which implements
126
-     * JobHandlerInterface
127
-     *
128
-     * @param string $classname
129
-     * @return JobHandlerInterface
130
-     * @throws BatchRequestException
131
-     */
132
-    public function instantiate_batch_job_handler_from_classname($classname)
133
-    {
134
-        if (! class_exists($classname)) {
135
-            throw new BatchRequestException(
136
-                sprintf(
137
-                    __(
138
-                        'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
139
-                        'event_espresso'
140
-                    ),
141
-                    $classname
142
-                )
143
-            );
144
-        }
145
-        $obj = new $classname;
146
-        if (! $obj instanceof JobHandlerInterface) {
147
-            throw new BatchRequestException(
148
-                sprintf(
149
-                    __(
150
-                        'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
151
-                        'event_espresso'
152
-                    ),
153
-                    $classname
154
-                )
155
-            );
156
-        }
157
-        return $obj;
158
-    }
124
+	/**
125
+	 * Instantiates an object of type $classname, which implements
126
+	 * JobHandlerInterface
127
+	 *
128
+	 * @param string $classname
129
+	 * @return JobHandlerInterface
130
+	 * @throws BatchRequestException
131
+	 */
132
+	public function instantiate_batch_job_handler_from_classname($classname)
133
+	{
134
+		if (! class_exists($classname)) {
135
+			throw new BatchRequestException(
136
+				sprintf(
137
+					__(
138
+						'The class %1$s does not exist, and so could not be used for running a job. It should implement JobHandlerInterface.',
139
+						'event_espresso'
140
+					),
141
+					$classname
142
+				)
143
+			);
144
+		}
145
+		$obj = new $classname;
146
+		if (! $obj instanceof JobHandlerInterface) {
147
+			throw new BatchRequestException(
148
+				sprintf(
149
+					__(
150
+						'The class %1$s does not implement JobHandlerInterface and so could not be used for running a job',
151
+						'event_espresso'
152
+					),
153
+					$classname
154
+				)
155
+			);
156
+		}
157
+		return $obj;
158
+	}
159 159
 
160 160
 
161
-    /**
162
-     * Forces a job to be cleaned up
163
-     *
164
-     * @param string $job_id
165
-     * @return JobStepResponse
166
-     * @throws BatchRequestException
167
-     */
168
-    public function cleanup_job($job_id)
169
-    {
170
-        try {
171
-            $this->_job_id = $job_id;
172
-            $job_parameters = JobParameters::load($this->_job_id);
173
-            $handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
174
-            // continue it
175
-            $response = $handler_obj->cleanup_job($job_parameters);
176
-            if (! $response instanceof JobStepResponse) {
177
-                throw new BatchRequestException(
178
-                    sprintf(
179
-                        __(
180
-                            'The class implementing JobHandlerInterface did not return a JobStepResponse when cleanup_job was called with job %1$s. It needs to return one or throw an Exception',
181
-                            'event_espresso'
182
-                        ),
183
-                        $this->_job_id
184
-                    )
185
-                );
186
-            }
187
-            $job_parameters->set_status(JobParameters::status_cleaned_up);
188
-            $job_parameters->delete();
189
-            return $response;
190
-        } catch (\Exception $e) {
191
-            $response = $this->_get_error_response($e, 'cleanup_job');
192
-        }
193
-        return $response;
194
-    }
161
+	/**
162
+	 * Forces a job to be cleaned up
163
+	 *
164
+	 * @param string $job_id
165
+	 * @return JobStepResponse
166
+	 * @throws BatchRequestException
167
+	 */
168
+	public function cleanup_job($job_id)
169
+	{
170
+		try {
171
+			$this->_job_id = $job_id;
172
+			$job_parameters = JobParameters::load($this->_job_id);
173
+			$handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
174
+			// continue it
175
+			$response = $handler_obj->cleanup_job($job_parameters);
176
+			if (! $response instanceof JobStepResponse) {
177
+				throw new BatchRequestException(
178
+					sprintf(
179
+						__(
180
+							'The class implementing JobHandlerInterface did not return a JobStepResponse when cleanup_job was called with job %1$s. It needs to return one or throw an Exception',
181
+							'event_espresso'
182
+						),
183
+						$this->_job_id
184
+					)
185
+				);
186
+			}
187
+			$job_parameters->set_status(JobParameters::status_cleaned_up);
188
+			$job_parameters->delete();
189
+			return $response;
190
+		} catch (\Exception $e) {
191
+			$response = $this->_get_error_response($e, 'cleanup_job');
192
+		}
193
+		return $response;
194
+	}
195 195
 
196 196
 
197
-    /**
198
-     * Creates a valid JobStepResponse object from an exception and method name.
199
-     *
200
-     * @param \Exception $exception
201
-     * @param string     $method_name
202
-     * @return JobStepResponse
203
-     */
204
-    protected function _get_error_response(\Exception $exception, $method_name)
205
-    {
206
-        if (! $this->_job_parameters instanceof JobParameters) {
207
-            $this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
208
-        }
209
-        $this->_job_parameters->set_status(JobParameters::status_error);
210
-        return new JobStepResponse(
211
-            $this->_job_parameters,
212
-            sprintf(
213
-                __(
214
-                    'An exception of type %1$s occurred while running %2$s. Its message was %3$s and had trace %4$s',
215
-                    'event_espresso'
216
-                ),
217
-                get_class($exception),
218
-                'BatchRunner::' . $method_name . '()',
219
-                $exception->getMessage(),
220
-                $exception->getTraceAsString()
221
-            )
222
-        );
223
-    }
197
+	/**
198
+	 * Creates a valid JobStepResponse object from an exception and method name.
199
+	 *
200
+	 * @param \Exception $exception
201
+	 * @param string     $method_name
202
+	 * @return JobStepResponse
203
+	 */
204
+	protected function _get_error_response(\Exception $exception, $method_name)
205
+	{
206
+		if (! $this->_job_parameters instanceof JobParameters) {
207
+			$this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
208
+		}
209
+		$this->_job_parameters->set_status(JobParameters::status_error);
210
+		return new JobStepResponse(
211
+			$this->_job_parameters,
212
+			sprintf(
213
+				__(
214
+					'An exception of type %1$s occurred while running %2$s. Its message was %3$s and had trace %4$s',
215
+					'event_espresso'
216
+				),
217
+				get_class($exception),
218
+				'BatchRunner::' . $method_name . '()',
219
+				$exception->getMessage(),
220
+				$exception->getTraceAsString()
221
+			)
222
+		);
223
+	}
224 224
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
             $obj = $this->instantiate_batch_job_handler_from_classname($batch_job_handler_class);
55 55
             $this->_job_parameters = new JobParameters($this->_job_id, $batch_job_handler_class, $request_data);
56 56
             $response = $obj->create_job($this->_job_parameters);
57
-            if (! $response instanceof JobStepResponse) {
57
+            if ( ! $response instanceof JobStepResponse) {
58 58
                 throw new BatchRequestException(
59 59
                     sprintf(
60 60
                         __(
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
                 );
67 67
             }
68 68
             $success = $this->_job_parameters->save(true);
69
-            if (! $success) {
69
+            if ( ! $success) {
70 70
                 throw new BatchRequestException(
71 71
                     sprintf(
72 72
                         __(
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
             $handler_obj = $this->instantiate_batch_job_handler_from_classname($this->_job_parameters->classname());
103 103
             // continue it
104 104
             $response = $handler_obj->continue_job($this->_job_parameters, $batch_size);
105
-            if (! $response instanceof JobStepResponse) {
105
+            if ( ! $response instanceof JobStepResponse) {
106 106
                 throw new BatchRequestException(
107 107
                     sprintf(
108 108
                         __(
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     public function instantiate_batch_job_handler_from_classname($classname)
133 133
     {
134
-        if (! class_exists($classname)) {
134
+        if ( ! class_exists($classname)) {
135 135
             throw new BatchRequestException(
136 136
                 sprintf(
137 137
                     __(
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
             );
144 144
         }
145 145
         $obj = new $classname;
146
-        if (! $obj instanceof JobHandlerInterface) {
146
+        if ( ! $obj instanceof JobHandlerInterface) {
147 147
             throw new BatchRequestException(
148 148
                 sprintf(
149 149
                     __(
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
             $handler_obj = $this->instantiate_batch_job_handler_from_classname($job_parameters->classname());
174 174
             // continue it
175 175
             $response = $handler_obj->cleanup_job($job_parameters);
176
-            if (! $response instanceof JobStepResponse) {
176
+            if ( ! $response instanceof JobStepResponse) {
177 177
                 throw new BatchRequestException(
178 178
                     sprintf(
179 179
                         __(
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
      */
204 204
     protected function _get_error_response(\Exception $exception, $method_name)
205 205
     {
206
-        if (! $this->_job_parameters instanceof JobParameters) {
206
+        if ( ! $this->_job_parameters instanceof JobParameters) {
207 207
             $this->_job_parameters = new JobParameters($this->_job_id, __('__Unknown__', 'event_espresso'), array());
208 208
         }
209 209
         $this->_job_parameters->set_status(JobParameters::status_error);
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
                     'event_espresso'
216 216
                 ),
217 217
                 get_class($exception),
218
-                'BatchRunner::' . $method_name . '()',
218
+                'BatchRunner::'.$method_name.'()',
219 219
                 $exception->getMessage(),
220 220
                 $exception->getTraceAsString()
221 221
             )
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/RegistrationsReport.php 2 patches
Indentation   +496 added lines, -496 removed lines patch added patch discarded remove patch
@@ -19,515 +19,515 @@
 block discarded – undo
19 19
  */
20 20
 class RegistrationsReport extends JobHandlerFile
21 21
 {
22
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23
-    /**
24
-     * Performs any necessary setup for starting the job. This is also a good
25
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
26
-     * when continue_job will be called
27
-     *
28
-     * @param JobParameters $job_parameters
29
-     * @throws BatchRequestException
30
-     * @return JobStepResponse
31
-     */
32
-    public function create_job(JobParameters $job_parameters)
33
-    {
34
-        $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
35
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
36
-            throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
37
-        }
38
-        $filepath = $this->create_file_from_job_with_name(
39
-            $job_parameters->job_id(),
40
-            $this->get_filename($event_id)
41
-        );
42
-        $job_parameters->add_extra_data('filepath', $filepath);
43
-        if ($job_parameters->request_datum('use_filters', false)) {
44
-            $query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
45
-        } else {
46
-            $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
47
-                array(
48
-                    'OR'                 => array(
49
-                        // don't include registrations from failed or abandoned transactions...
50
-                        'Transaction.STS_ID' => array(
51
-                            'NOT IN',
52
-                            array(
53
-                                \EEM_Transaction::failed_status_code,
54
-                                \EEM_Transaction::abandoned_status_code,
55
-                            ),
56
-                        ),
57
-                        // unless the registration is approved, in which case include it regardless of transaction status
58
-                        'STS_ID'             => \EEM_Registration::status_id_approved,
59
-                    ),
60
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
61
-                ),
62
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
63
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
64
-                'caps'       => \EEM_Base::caps_read_admin,
65
-            ), $event_id);
66
-            if ($event_id) {
67
-                $query_params[0]['EVT_ID'] = $event_id;
68
-            } else {
69
-                $query_params['force_join'][] = 'Event';
70
-            }
71
-        }
72
-        if (! isset($query_params['force_join'])) {
73
-            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
74
-        }
75
-        $job_parameters->add_extra_data('query_params', $query_params);
76
-        $question_labels = $this->_get_question_labels($query_params);
77
-        $job_parameters->add_extra_data('question_labels', $question_labels);
78
-        $job_parameters->set_job_size(
79
-            \EEM_Registration::instance()->count(
80
-                array_diff_key(
81
-                    $query_params,
82
-                    array_flip(
83
-                        array('limit')
84
-                    )
85
-                )
86
-            )
87
-        );
88
-        // we should also set the header columns
89
-        $csv_data_for_row = $this->get_csv_data_for(
90
-            $event_id,
91
-            0,
92
-            1,
93
-            $job_parameters->extra_datum('question_labels'),
94
-            $job_parameters->extra_datum('query_params')
95
-        );
96
-        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
97
-        // if we actually processed a row there, record it
98
-        if ($job_parameters->job_size()) {
99
-            $job_parameters->mark_processed(1);
100
-        }
101
-        return new JobStepResponse(
102
-            $job_parameters,
103
-            __('Registrations report started successfully...', 'event_espresso')
104
-        );
105
-    }
22
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23
+	/**
24
+	 * Performs any necessary setup for starting the job. This is also a good
25
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
26
+	 * when continue_job will be called
27
+	 *
28
+	 * @param JobParameters $job_parameters
29
+	 * @throws BatchRequestException
30
+	 * @return JobStepResponse
31
+	 */
32
+	public function create_job(JobParameters $job_parameters)
33
+	{
34
+		$event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
35
+		if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
36
+			throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
37
+		}
38
+		$filepath = $this->create_file_from_job_with_name(
39
+			$job_parameters->job_id(),
40
+			$this->get_filename($event_id)
41
+		);
42
+		$job_parameters->add_extra_data('filepath', $filepath);
43
+		if ($job_parameters->request_datum('use_filters', false)) {
44
+			$query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
45
+		} else {
46
+			$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
47
+				array(
48
+					'OR'                 => array(
49
+						// don't include registrations from failed or abandoned transactions...
50
+						'Transaction.STS_ID' => array(
51
+							'NOT IN',
52
+							array(
53
+								\EEM_Transaction::failed_status_code,
54
+								\EEM_Transaction::abandoned_status_code,
55
+							),
56
+						),
57
+						// unless the registration is approved, in which case include it regardless of transaction status
58
+						'STS_ID'             => \EEM_Registration::status_id_approved,
59
+					),
60
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
61
+				),
62
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
63
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
64
+				'caps'       => \EEM_Base::caps_read_admin,
65
+			), $event_id);
66
+			if ($event_id) {
67
+				$query_params[0]['EVT_ID'] = $event_id;
68
+			} else {
69
+				$query_params['force_join'][] = 'Event';
70
+			}
71
+		}
72
+		if (! isset($query_params['force_join'])) {
73
+			$query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
74
+		}
75
+		$job_parameters->add_extra_data('query_params', $query_params);
76
+		$question_labels = $this->_get_question_labels($query_params);
77
+		$job_parameters->add_extra_data('question_labels', $question_labels);
78
+		$job_parameters->set_job_size(
79
+			\EEM_Registration::instance()->count(
80
+				array_diff_key(
81
+					$query_params,
82
+					array_flip(
83
+						array('limit')
84
+					)
85
+				)
86
+			)
87
+		);
88
+		// we should also set the header columns
89
+		$csv_data_for_row = $this->get_csv_data_for(
90
+			$event_id,
91
+			0,
92
+			1,
93
+			$job_parameters->extra_datum('question_labels'),
94
+			$job_parameters->extra_datum('query_params')
95
+		);
96
+		\EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
97
+		// if we actually processed a row there, record it
98
+		if ($job_parameters->job_size()) {
99
+			$job_parameters->mark_processed(1);
100
+		}
101
+		return new JobStepResponse(
102
+			$job_parameters,
103
+			__('Registrations report started successfully...', 'event_espresso')
104
+		);
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * Gets the filename
110
-     *
111
-     * @return string
112
-     */
113
-    protected function get_filename()
114
-    {
115
-        return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
116
-    }
108
+	/**
109
+	 * Gets the filename
110
+	 *
111
+	 * @return string
112
+	 */
113
+	protected function get_filename()
114
+	{
115
+		return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * Gets the questions which are to be used for this report, so they
121
-     * can be remembered for later
122
-     *
123
-     * @param array $registration_query_params
124
-     * @return array question admin labels to be used for this report
125
-     */
126
-    protected function _get_question_labels($registration_query_params)
127
-    {
128
-        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
129
-        $question_query_params = array();
130
-        if ($where !== null) {
131
-            $question_query_params = array(
132
-                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
133
-            );
134
-        }
135
-        $question_query_params[0]['QST_system'] = array(
136
-            'NOT_IN',
137
-            array_keys(\EEM_Attendee::instance()->system_question_to_attendee_field_mapping()),
138
-        );
139
-        if (apply_filters(
140
-            'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
141
-            false,
142
-            $registration_query_params
143
-        )) {
144
-            $question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
145
-        }
146
-        $question_query_params['group_by'] = array('QST_ID');
147
-        return array_unique(\EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
148
-    }
119
+	/**
120
+	 * Gets the questions which are to be used for this report, so they
121
+	 * can be remembered for later
122
+	 *
123
+	 * @param array $registration_query_params
124
+	 * @return array question admin labels to be used for this report
125
+	 */
126
+	protected function _get_question_labels($registration_query_params)
127
+	{
128
+		$where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
129
+		$question_query_params = array();
130
+		if ($where !== null) {
131
+			$question_query_params = array(
132
+				$this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
133
+			);
134
+		}
135
+		$question_query_params[0]['QST_system'] = array(
136
+			'NOT_IN',
137
+			array_keys(\EEM_Attendee::instance()->system_question_to_attendee_field_mapping()),
138
+		);
139
+		if (apply_filters(
140
+			'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
141
+			false,
142
+			$registration_query_params
143
+		)) {
144
+			$question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
145
+		}
146
+		$question_query_params['group_by'] = array('QST_ID');
147
+		return array_unique(\EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
148
+	}
149 149
 
150 150
 
151
-    /**
152
-     * Takes where params meant for registrations and changes them to work for questions
153
-     *
154
-     * @param array $reg_where_params
155
-     * @return array
156
-     */
157
-    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
158
-    {
159
-        $question_where_params = array();
160
-        foreach ($reg_where_params as $key => $val) {
161
-            if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
162
-                $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
163
-            } else {
164
-                // it's a normal where condition
165
-                $question_where_params['Question_Group.Event.Registration.' . $key] = $val;
166
-            }
167
-        }
168
-        return $question_where_params;
169
-    }
151
+	/**
152
+	 * Takes where params meant for registrations and changes them to work for questions
153
+	 *
154
+	 * @param array $reg_where_params
155
+	 * @return array
156
+	 */
157
+	protected function _change_registration_where_params_to_question_where_params($reg_where_params)
158
+	{
159
+		$question_where_params = array();
160
+		foreach ($reg_where_params as $key => $val) {
161
+			if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
162
+				$question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
163
+			} else {
164
+				// it's a normal where condition
165
+				$question_where_params['Question_Group.Event.Registration.' . $key] = $val;
166
+			}
167
+		}
168
+		return $question_where_params;
169
+	}
170 170
 
171 171
 
172
-    /**
173
-     * Performs another step of the job
174
-     *
175
-     * @param JobParameters $job_parameters
176
-     * @param int           $batch_size
177
-     * @return JobStepResponse
178
-     * @throws \EE_Error
179
-     */
180
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
181
-    {
182
-        if ($job_parameters->units_processed() < $job_parameters->job_size()) {
183
-            $csv_data = $this->get_csv_data_for(
184
-                $job_parameters->request_datum('EVT_ID', '0'),
185
-                $job_parameters->units_processed(),
186
-                $batch_size,
187
-                $job_parameters->extra_datum('question_labels'),
188
-                $job_parameters->extra_datum('query_params')
189
-            );
190
-            \EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
191
-            $units_processed = count($csv_data);
192
-        } else {
193
-            $units_processed = 0;
194
-        }
195
-        $job_parameters->mark_processed($units_processed);
196
-        $extra_response_data = array(
197
-            'file_url' => '',
198
-        );
199
-        if ($units_processed < $batch_size) {
200
-            $job_parameters->set_status(JobParameters::status_complete);
201
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
202
-        }
172
+	/**
173
+	 * Performs another step of the job
174
+	 *
175
+	 * @param JobParameters $job_parameters
176
+	 * @param int           $batch_size
177
+	 * @return JobStepResponse
178
+	 * @throws \EE_Error
179
+	 */
180
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
181
+	{
182
+		if ($job_parameters->units_processed() < $job_parameters->job_size()) {
183
+			$csv_data = $this->get_csv_data_for(
184
+				$job_parameters->request_datum('EVT_ID', '0'),
185
+				$job_parameters->units_processed(),
186
+				$batch_size,
187
+				$job_parameters->extra_datum('question_labels'),
188
+				$job_parameters->extra_datum('query_params')
189
+			);
190
+			\EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
191
+			$units_processed = count($csv_data);
192
+		} else {
193
+			$units_processed = 0;
194
+		}
195
+		$job_parameters->mark_processed($units_processed);
196
+		$extra_response_data = array(
197
+			'file_url' => '',
198
+		);
199
+		if ($units_processed < $batch_size) {
200
+			$job_parameters->set_status(JobParameters::status_complete);
201
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
202
+		}
203 203
 
204
-        return new JobStepResponse(
205
-            $job_parameters,
206
-            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
207
-            $extra_response_data
208
-        );
209
-    }
204
+		return new JobStepResponse(
205
+			$job_parameters,
206
+			sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
207
+			$extra_response_data
208
+		);
209
+	}
210 210
 
211 211
 
212
-    /**
213
-     * Gets the csv data for a batch of registrations
214
-     *
215
-     * @param int|null $event_id
216
-     * @param int      $offset
217
-     * @param int      $limit
218
-     * @param array    $question_labels the IDs for all the questions which were answered by someone in this selection
219
-     * @param array    $query_params    for using where querying the model
220
-     * @return array top-level keys are numeric, next-level keys are column headers
221
-     */
222
-    public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
223
-    {
224
-        $reg_fields_to_include = array(
225
-            'TXN_ID',
226
-            'ATT_ID',
227
-            'REG_ID',
228
-            'REG_date',
229
-            'REG_code',
230
-            'REG_count',
231
-            'REG_final_price',
232
-        );
233
-        $att_fields_to_include = array(
234
-            'ATT_fname',
235
-            'ATT_lname',
236
-            'ATT_email',
237
-            'ATT_address',
238
-            'ATT_address2',
239
-            'ATT_city',
240
-            'STA_ID',
241
-            'CNT_ISO',
242
-            'ATT_zip',
243
-            'ATT_phone',
244
-        );
245
-        $registrations_csv_ready_array = array();
246
-        $reg_model = \EE_Registry::instance()->load_model('Registration');
247
-        $query_params['limit'] = array($offset, $limit);
248
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
249
-        $registration_ids = array();
250
-        foreach ($registration_rows as $reg_row) {
251
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
252
-        }
253
-        foreach ($registration_rows as $reg_row) {
254
-            if (is_array($reg_row)) {
255
-                $reg_csv_array = array();
256
-                if (! $event_id) {
257
-                    // get the event's name and Id
258
-                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(
259
-                        __('%1$s (%2$s)', 'event_espresso'),
260
-                        \EEH_Export::prepare_value_from_db_for_display(
261
-                            \EEM_Event::instance(),
262
-                            'EVT_name',
263
-                            $reg_row['Event_CPT.post_title']
264
-                        ),
265
-                        $reg_row['Event_CPT.ID']
266
-                    );
267
-                }
268
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
269
-                /*@var $reg_row EE_Registration */
270
-                foreach ($reg_fields_to_include as $field_name) {
271
-                    $field = $reg_model->field_settings_for($field_name);
272
-                    if ($field_name == 'REG_final_price') {
273
-                        $value = \EEH_Export::prepare_value_from_db_for_display(
274
-                            $reg_model,
275
-                            $field_name,
276
-                            $reg_row['Registration.REG_final_price'],
277
-                            'localized_float'
278
-                        );
279
-                    } elseif ($field_name == 'REG_count') {
280
-                        $value = sprintf(
281
-                            __('%1$s of %2$s', 'event_espresso'),
282
-                            \EEH_Export::prepare_value_from_db_for_display(
283
-                                $reg_model,
284
-                                'REG_count',
285
-                                $reg_row['Registration.REG_count']
286
-                            ),
287
-                            \EEH_Export::prepare_value_from_db_for_display(
288
-                                $reg_model,
289
-                                'REG_group_size',
290
-                                $reg_row['Registration.REG_group_size']
291
-                            )
292
-                        );
293
-                    } elseif ($field_name == 'REG_date') {
294
-                        $value = \EEH_Export::prepare_value_from_db_for_display(
295
-                            $reg_model,
296
-                            $field_name,
297
-                            $reg_row['Registration.REG_date'],
298
-                            'no_html'
299
-                        );
300
-                    } else {
301
-                        $value = \EEH_Export::prepare_value_from_db_for_display(
302
-                            $reg_model,
303
-                            $field_name,
304
-                            $reg_row[$field->get_qualified_column()]
305
-                        );
306
-                    }
307
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
308
-                    if ($field_name == 'REG_final_price') {
309
-                        // add a column named Currency after the final price
310
-                        $reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
311
-                    }
312
-                }
313
-                // get pretty status
314
-                $stati = \EEM_Status::instance()->localized_status(array(
315
-                    $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
316
-                    $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
317
-                ), false, 'sentence');
318
-                $reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
319
-                // get pretty transaction status
320
-                $reg_csv_array[__("Transaction Status", 'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
321
-                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
322
-                    ? \EEH_Export::prepare_value_from_db_for_display(
323
-                        \EEM_Transaction::instance(),
324
-                        'TXN_total',
325
-                        $reg_row['TransactionTable.TXN_total'],
326
-                        'localized_float'
327
-                    ) : '0.00';
328
-                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
329
-                    ? \EEH_Export::prepare_value_from_db_for_display(
330
-                        \EEM_Transaction::instance(),
331
-                        'TXN_paid',
332
-                        $reg_row['TransactionTable.TXN_paid'],
333
-                        'localized_float'
334
-                    ) : '0.00';
335
-                $payment_methods = array();
336
-                $gateway_txn_ids_etc = array();
337
-                $payment_times = array();
338
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
339
-                    $payments_info = \EEM_Payment::instance()->get_all_wpdb_results(
340
-                        array(
341
-                            array(
342
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
343
-                                'STS_ID' => \EEM_Payment::status_id_approved,
344
-                            ),
345
-                            'force_join' => array('Payment_Method'),
346
-                        ),
347
-                        ARRAY_A,
348
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
349
-                    );
350
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
351
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
352
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
353
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
354
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
355
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
356
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
357
-                    }
358
-                }
359
-                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
360
-                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
361
-                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
362
-                // get whether or not the user has checked in
363
-                $reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related(
364
-                    $reg_row['Registration.REG_ID'],
365
-                    'Checkin'
366
-                );
367
-                // get ticket of registration and its price
368
-                $ticket_model = \EE_Registry::instance()->load_model('Ticket');
369
-                if ($reg_row['Ticket.TKT_ID']) {
370
-                    $ticket_name = \EEH_Export::prepare_value_from_db_for_display(
371
-                        $ticket_model,
372
-                        'TKT_name',
373
-                        $reg_row['Ticket.TKT_name']
374
-                    );
375
-                    $datetimes_strings = array();
376
-                    foreach (\EEM_Datetime::instance()->get_all_wpdb_results(
377
-                        array(
378
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
379
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
380
-                            'default_where_conditions' => 'none',
381
-                        )
382
-                    ) as $datetime) {
383
-                        $datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(
384
-                            \EEM_Datetime::instance(),
385
-                            'DTT_EVT_start',
386
-                            $datetime['Datetime.DTT_EVT_start']
387
-                        );
388
-                    }
389
-                } else {
390
-                    $ticket_name = __('Unknown', 'event_espresso');
391
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
392
-                }
393
-                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
394
-                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
395
-                // get datetime(s) of registration
396
-                // add attendee columns
397
-                foreach ($att_fields_to_include as $att_field_name) {
398
-                    $field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
399
-                    if ($reg_row['Attendee_CPT.ID']) {
400
-                        if ($att_field_name == 'STA_ID') {
401
-                            $value = \EEM_State::instance()->get_var(
402
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
403
-                                'STA_name'
404
-                            );
405
-                        } elseif ($att_field_name == 'CNT_ISO') {
406
-                            $value = \EEM_Country::instance()->get_var(
407
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
408
-                                'CNT_name'
409
-                            );
410
-                        } else {
411
-                            $value = \EEH_Export::prepare_value_from_db_for_display(
412
-                                \EEM_Attendee::instance(),
413
-                                $att_field_name,
414
-                                $reg_row[$field_obj->get_qualified_column()]
415
-                            );
416
-                        }
417
-                    } else {
418
-                        $value = '';
419
-                    }
420
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
421
-                }
422
-                // make sure each registration has the same questions in the same order
423
-                foreach ($question_labels as $question_label) {
424
-                    if (! isset($reg_csv_array[$question_label])) {
425
-                        $reg_csv_array[$question_label] = null;
426
-                    }
427
-                }
428
-                $answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
429
-                    array('REG_ID' => $reg_row['Registration.REG_ID']),
430
-                    'force_join' => array('Question'),
431
-                ));
432
-                // now fill out the questions THEY answered
433
-                foreach ($answers as $answer_row) {
434
-                    if ($answer_row['Question.QST_ID']) {
435
-                        $question_label = \EEH_Export::prepare_value_from_db_for_display(
436
-                            \EEM_Question::instance(),
437
-                            'QST_admin_label',
438
-                            $answer_row['Question.QST_admin_label']
439
-                        );
440
-                    } else {
441
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
442
-                    }
443
-                    if (isset($answer_row['Question.QST_type'])
444
-                        && $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
445
-                    ) {
446
-                        $reg_csv_array[$question_label] = \EEM_State::instance()->get_state_name_by_ID(
447
-                            $answer_row['Answer.ANS_value']
448
-                        );
449
-                    } else {
450
-                        // this isn't for html, so don't show html entities
451
-                        $reg_csv_array[$question_label] = html_entity_decode(
452
-                            \EEH_Export::prepare_value_from_db_for_display(
453
-                                \EEM_Answer::instance(),
454
-                                'ANS_value',
455
-                                $answer_row['Answer.ANS_value']
456
-                            )
457
-                        );
458
-                    }
459
-                }
460
-                /**
461
-                 * Filter to change the contents of each row of the registrations report CSV file.
462
-                 * This can be used to add or remote columns from the CSV file, or change their values.                 *
463
-                 * Note: it has this name because originally that's where this filter resided,
464
-                 * and we've left its name as-is for backward compatibility.
465
-                 * Note when using: all rows in the CSV should have the same columns.
466
-                 *
467
-                 * @param array $reg_csv_array keys are column-header names, and values are that columns' value
468
-                 *                             in this row
469
-                 * @param array $reg_row       is the row from the database's wp_esp_registration table
470
-                 */
471
-                $registrations_csv_ready_array[] = apply_filters(
472
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
473
-                    $reg_csv_array,
474
-                    $reg_row
475
-                );
476
-            }
477
-        }
478
-        // if we couldn't export anything, we want to at least show the column headers
479
-        if (empty($registrations_csv_ready_array)) {
480
-            $reg_csv_array = array();
481
-            $model_and_fields_to_include = array(
482
-                'Registration' => $reg_fields_to_include,
483
-                'Attendee'     => $att_fields_to_include,
484
-            );
485
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
486
-                $model = \EE_Registry::instance()->load_model($model_name);
487
-                foreach ($field_list as $field_name) {
488
-                    $field = $model->field_settings_for($field_name);
489
-                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
490
-                }
491
-            }
492
-            $registrations_csv_ready_array[] = $reg_csv_array;
493
-        }
494
-        return $registrations_csv_ready_array;
495
-    }
212
+	/**
213
+	 * Gets the csv data for a batch of registrations
214
+	 *
215
+	 * @param int|null $event_id
216
+	 * @param int      $offset
217
+	 * @param int      $limit
218
+	 * @param array    $question_labels the IDs for all the questions which were answered by someone in this selection
219
+	 * @param array    $query_params    for using where querying the model
220
+	 * @return array top-level keys are numeric, next-level keys are column headers
221
+	 */
222
+	public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
223
+	{
224
+		$reg_fields_to_include = array(
225
+			'TXN_ID',
226
+			'ATT_ID',
227
+			'REG_ID',
228
+			'REG_date',
229
+			'REG_code',
230
+			'REG_count',
231
+			'REG_final_price',
232
+		);
233
+		$att_fields_to_include = array(
234
+			'ATT_fname',
235
+			'ATT_lname',
236
+			'ATT_email',
237
+			'ATT_address',
238
+			'ATT_address2',
239
+			'ATT_city',
240
+			'STA_ID',
241
+			'CNT_ISO',
242
+			'ATT_zip',
243
+			'ATT_phone',
244
+		);
245
+		$registrations_csv_ready_array = array();
246
+		$reg_model = \EE_Registry::instance()->load_model('Registration');
247
+		$query_params['limit'] = array($offset, $limit);
248
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
249
+		$registration_ids = array();
250
+		foreach ($registration_rows as $reg_row) {
251
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
252
+		}
253
+		foreach ($registration_rows as $reg_row) {
254
+			if (is_array($reg_row)) {
255
+				$reg_csv_array = array();
256
+				if (! $event_id) {
257
+					// get the event's name and Id
258
+					$reg_csv_array[__('Event', 'event_espresso')] = sprintf(
259
+						__('%1$s (%2$s)', 'event_espresso'),
260
+						\EEH_Export::prepare_value_from_db_for_display(
261
+							\EEM_Event::instance(),
262
+							'EVT_name',
263
+							$reg_row['Event_CPT.post_title']
264
+						),
265
+						$reg_row['Event_CPT.ID']
266
+					);
267
+				}
268
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
269
+				/*@var $reg_row EE_Registration */
270
+				foreach ($reg_fields_to_include as $field_name) {
271
+					$field = $reg_model->field_settings_for($field_name);
272
+					if ($field_name == 'REG_final_price') {
273
+						$value = \EEH_Export::prepare_value_from_db_for_display(
274
+							$reg_model,
275
+							$field_name,
276
+							$reg_row['Registration.REG_final_price'],
277
+							'localized_float'
278
+						);
279
+					} elseif ($field_name == 'REG_count') {
280
+						$value = sprintf(
281
+							__('%1$s of %2$s', 'event_espresso'),
282
+							\EEH_Export::prepare_value_from_db_for_display(
283
+								$reg_model,
284
+								'REG_count',
285
+								$reg_row['Registration.REG_count']
286
+							),
287
+							\EEH_Export::prepare_value_from_db_for_display(
288
+								$reg_model,
289
+								'REG_group_size',
290
+								$reg_row['Registration.REG_group_size']
291
+							)
292
+						);
293
+					} elseif ($field_name == 'REG_date') {
294
+						$value = \EEH_Export::prepare_value_from_db_for_display(
295
+							$reg_model,
296
+							$field_name,
297
+							$reg_row['Registration.REG_date'],
298
+							'no_html'
299
+						);
300
+					} else {
301
+						$value = \EEH_Export::prepare_value_from_db_for_display(
302
+							$reg_model,
303
+							$field_name,
304
+							$reg_row[$field->get_qualified_column()]
305
+						);
306
+					}
307
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
308
+					if ($field_name == 'REG_final_price') {
309
+						// add a column named Currency after the final price
310
+						$reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
311
+					}
312
+				}
313
+				// get pretty status
314
+				$stati = \EEM_Status::instance()->localized_status(array(
315
+					$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
316
+					$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
317
+				), false, 'sentence');
318
+				$reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
319
+				// get pretty transaction status
320
+				$reg_csv_array[__("Transaction Status", 'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
321
+				$reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
322
+					? \EEH_Export::prepare_value_from_db_for_display(
323
+						\EEM_Transaction::instance(),
324
+						'TXN_total',
325
+						$reg_row['TransactionTable.TXN_total'],
326
+						'localized_float'
327
+					) : '0.00';
328
+				$reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
329
+					? \EEH_Export::prepare_value_from_db_for_display(
330
+						\EEM_Transaction::instance(),
331
+						'TXN_paid',
332
+						$reg_row['TransactionTable.TXN_paid'],
333
+						'localized_float'
334
+					) : '0.00';
335
+				$payment_methods = array();
336
+				$gateway_txn_ids_etc = array();
337
+				$payment_times = array();
338
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
339
+					$payments_info = \EEM_Payment::instance()->get_all_wpdb_results(
340
+						array(
341
+							array(
342
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
343
+								'STS_ID' => \EEM_Payment::status_id_approved,
344
+							),
345
+							'force_join' => array('Payment_Method'),
346
+						),
347
+						ARRAY_A,
348
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
349
+					);
350
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
351
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
352
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
353
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
354
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
355
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
356
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
357
+					}
358
+				}
359
+				$reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
360
+				$reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
361
+				$reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
362
+				// get whether or not the user has checked in
363
+				$reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related(
364
+					$reg_row['Registration.REG_ID'],
365
+					'Checkin'
366
+				);
367
+				// get ticket of registration and its price
368
+				$ticket_model = \EE_Registry::instance()->load_model('Ticket');
369
+				if ($reg_row['Ticket.TKT_ID']) {
370
+					$ticket_name = \EEH_Export::prepare_value_from_db_for_display(
371
+						$ticket_model,
372
+						'TKT_name',
373
+						$reg_row['Ticket.TKT_name']
374
+					);
375
+					$datetimes_strings = array();
376
+					foreach (\EEM_Datetime::instance()->get_all_wpdb_results(
377
+						array(
378
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
379
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
380
+							'default_where_conditions' => 'none',
381
+						)
382
+					) as $datetime) {
383
+						$datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(
384
+							\EEM_Datetime::instance(),
385
+							'DTT_EVT_start',
386
+							$datetime['Datetime.DTT_EVT_start']
387
+						);
388
+					}
389
+				} else {
390
+					$ticket_name = __('Unknown', 'event_espresso');
391
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
392
+				}
393
+				$reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
394
+				$reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
395
+				// get datetime(s) of registration
396
+				// add attendee columns
397
+				foreach ($att_fields_to_include as $att_field_name) {
398
+					$field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
399
+					if ($reg_row['Attendee_CPT.ID']) {
400
+						if ($att_field_name == 'STA_ID') {
401
+							$value = \EEM_State::instance()->get_var(
402
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
403
+								'STA_name'
404
+							);
405
+						} elseif ($att_field_name == 'CNT_ISO') {
406
+							$value = \EEM_Country::instance()->get_var(
407
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
408
+								'CNT_name'
409
+							);
410
+						} else {
411
+							$value = \EEH_Export::prepare_value_from_db_for_display(
412
+								\EEM_Attendee::instance(),
413
+								$att_field_name,
414
+								$reg_row[$field_obj->get_qualified_column()]
415
+							);
416
+						}
417
+					} else {
418
+						$value = '';
419
+					}
420
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
421
+				}
422
+				// make sure each registration has the same questions in the same order
423
+				foreach ($question_labels as $question_label) {
424
+					if (! isset($reg_csv_array[$question_label])) {
425
+						$reg_csv_array[$question_label] = null;
426
+					}
427
+				}
428
+				$answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
429
+					array('REG_ID' => $reg_row['Registration.REG_ID']),
430
+					'force_join' => array('Question'),
431
+				));
432
+				// now fill out the questions THEY answered
433
+				foreach ($answers as $answer_row) {
434
+					if ($answer_row['Question.QST_ID']) {
435
+						$question_label = \EEH_Export::prepare_value_from_db_for_display(
436
+							\EEM_Question::instance(),
437
+							'QST_admin_label',
438
+							$answer_row['Question.QST_admin_label']
439
+						);
440
+					} else {
441
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
442
+					}
443
+					if (isset($answer_row['Question.QST_type'])
444
+						&& $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
445
+					) {
446
+						$reg_csv_array[$question_label] = \EEM_State::instance()->get_state_name_by_ID(
447
+							$answer_row['Answer.ANS_value']
448
+						);
449
+					} else {
450
+						// this isn't for html, so don't show html entities
451
+						$reg_csv_array[$question_label] = html_entity_decode(
452
+							\EEH_Export::prepare_value_from_db_for_display(
453
+								\EEM_Answer::instance(),
454
+								'ANS_value',
455
+								$answer_row['Answer.ANS_value']
456
+							)
457
+						);
458
+					}
459
+				}
460
+				/**
461
+				 * Filter to change the contents of each row of the registrations report CSV file.
462
+				 * This can be used to add or remote columns from the CSV file, or change their values.                 *
463
+				 * Note: it has this name because originally that's where this filter resided,
464
+				 * and we've left its name as-is for backward compatibility.
465
+				 * Note when using: all rows in the CSV should have the same columns.
466
+				 *
467
+				 * @param array $reg_csv_array keys are column-header names, and values are that columns' value
468
+				 *                             in this row
469
+				 * @param array $reg_row       is the row from the database's wp_esp_registration table
470
+				 */
471
+				$registrations_csv_ready_array[] = apply_filters(
472
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
473
+					$reg_csv_array,
474
+					$reg_row
475
+				);
476
+			}
477
+		}
478
+		// if we couldn't export anything, we want to at least show the column headers
479
+		if (empty($registrations_csv_ready_array)) {
480
+			$reg_csv_array = array();
481
+			$model_and_fields_to_include = array(
482
+				'Registration' => $reg_fields_to_include,
483
+				'Attendee'     => $att_fields_to_include,
484
+			);
485
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
486
+				$model = \EE_Registry::instance()->load_model($model_name);
487
+				foreach ($field_list as $field_name) {
488
+					$field = $model->field_settings_for($field_name);
489
+					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
490
+				}
491
+			}
492
+			$registrations_csv_ready_array[] = $reg_csv_array;
493
+		}
494
+		return $registrations_csv_ready_array;
495
+	}
496 496
 
497 497
 
498
-    /**
499
-     * Counts total unit to process
500
-     *
501
-     * @deprecated since 4.9.19
502
-     * @param int|array $event_id
503
-     * @return int
504
-     */
505
-    public function count_units_to_process($event_id)
506
-    {
507
-        // use the legacy filter
508
-        if ($event_id) {
509
-            $query_params[0]['EVT_ID'] = $event_id;
510
-        } else {
511
-            $query_params['force_join'][] = 'Event';
512
-        }
513
-        return \EEM_Registration::instance()->count($query_params);
514
-    }
498
+	/**
499
+	 * Counts total unit to process
500
+	 *
501
+	 * @deprecated since 4.9.19
502
+	 * @param int|array $event_id
503
+	 * @return int
504
+	 */
505
+	public function count_units_to_process($event_id)
506
+	{
507
+		// use the legacy filter
508
+		if ($event_id) {
509
+			$query_params[0]['EVT_ID'] = $event_id;
510
+		} else {
511
+			$query_params['force_join'][] = 'Event';
512
+		}
513
+		return \EEM_Registration::instance()->count($query_params);
514
+	}
515 515
 
516 516
 
517
-    /**
518
-     * Performs any clean-up logic when we know the job is completed.
519
-     * In this case, we delete the temporary file
520
-     *
521
-     * @param JobParameters $job_parameters
522
-     * @return boolean
523
-     */
524
-    public function cleanup_job(JobParameters $job_parameters)
525
-    {
526
-        $this->_file_helper->delete(
527
-            \EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
528
-            true,
529
-            'd'
530
-        );
531
-        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
532
-    }
517
+	/**
518
+	 * Performs any clean-up logic when we know the job is completed.
519
+	 * In this case, we delete the temporary file
520
+	 *
521
+	 * @param JobParameters $job_parameters
522
+	 * @return boolean
523
+	 */
524
+	public function cleanup_job(JobParameters $job_parameters)
525
+	{
526
+		$this->_file_helper->delete(
527
+			\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
528
+			true,
529
+			'd'
530
+		);
531
+		return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
532
+	}
533 533
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
     public function create_job(JobParameters $job_parameters)
33 33
     {
34 34
         $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
35
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
35
+        if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
36 36
             throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
37 37
         }
38 38
         $filepath = $this->create_file_from_job_with_name(
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
                 $query_params['force_join'][] = 'Event';
70 70
             }
71 71
         }
72
-        if (! isset($query_params['force_join'])) {
72
+        if ( ! isset($query_params['force_join'])) {
73 73
             $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
74 74
         }
75 75
         $job_parameters->add_extra_data('query_params', $query_params);
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
                 $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
163 163
             } else {
164 164
                 // it's a normal where condition
165
-                $question_where_params['Question_Group.Event.Registration.' . $key] = $val;
165
+                $question_where_params['Question_Group.Event.Registration.'.$key] = $val;
166 166
             }
167 167
         }
168 168
         return $question_where_params;
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         foreach ($registration_rows as $reg_row) {
254 254
             if (is_array($reg_row)) {
255 255
                 $reg_csv_array = array();
256
-                if (! $event_id) {
256
+                if ( ! $event_id) {
257 257
                     // get the event's name and Id
258 258
                     $reg_csv_array[__('Event', 'event_espresso')] = sprintf(
259 259
                         __('%1$s (%2$s)', 'event_espresso'),
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
                 }
422 422
                 // make sure each registration has the same questions in the same order
423 423
                 foreach ($question_labels as $question_label) {
424
-                    if (! isset($reg_csv_array[$question_label])) {
424
+                    if ( ! isset($reg_csv_array[$question_label])) {
425 425
                         $reg_csv_array[$question_label] = null;
426 426
                     }
427 427
                 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/DatetimeOffsetFix.php 2 patches
Indentation   +466 added lines, -466 removed lines patch added patch discarded remove patch
@@ -24,470 +24,470 @@
 block discarded – undo
24 24
 class DatetimeOffsetFix extends JobHandler
25 25
 {
26 26
 
27
-    /**
28
-     * Key for the option used to track which models have been processed when doing the batches.
29
-     */
30
-    const MODELS_TO_PROCESS_OPTION_KEY = 'ee_models_processed_for_datetime_offset_fix';
31
-
32
-
33
-    const COUNT_OF_MODELS_PROCESSED = 'ee_count_of_ee_models_processed_for_datetime_offset_fixed';
34
-
35
-    /**
36
-     * Key for the option used to track what the current offset is that will be applied when this tool is executed.
37
-     */
38
-    const OFFSET_TO_APPLY_OPTION_KEY = 'ee_datetime_offset_fix_offset_to_apply';
39
-
40
-
41
-    const OPTION_KEY_OFFSET_RANGE_START_DATE = 'ee_datetime_offset_start_date_range';
42
-
43
-
44
-    const OPTION_KEY_OFFSET_RANGE_END_DATE = 'ee_datetime_offset_end_date_range';
45
-
46
-
47
-    /**
48
-     * String labelling the datetime offset fix type for change-log entries.
49
-     */
50
-    const DATETIME_OFFSET_FIX_CHANGELOG_TYPE = 'datetime_offset_fix';
51
-
52
-
53
-    /**
54
-     * String labelling a datetime offset fix error for change-log entries.
55
-     */
56
-    const DATETIME_OFFSET_FIX_CHANGELOG_ERROR_TYPE = 'datetime_offset_fix_error';
57
-
58
-    /**
59
-     * @var EEM_Base[]
60
-     */
61
-    protected $models_with_datetime_fields = array();
62
-
63
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
64
-    /**
65
-     * Performs any necessary setup for starting the job. This is also a good
66
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
67
-     * when continue_job will be called
68
-     *
69
-     * @param JobParameters $job_parameters
70
-     * @return JobStepResponse
71
-     * @throws EE_Error
72
-     * @throws InvalidArgumentException
73
-     * @throws InvalidDataTypeException
74
-     * @throws InvalidInterfaceException
75
-     */
76
-    public function create_job(JobParameters $job_parameters)
77
-    {
78
-        $models_with_datetime_fields = $this->getModelsWithDatetimeFields();
79
-        // we'll be doing each model as a batch.
80
-        $job_parameters->set_job_size(count($models_with_datetime_fields));
81
-        return new JobStepResponse(
82
-            $job_parameters,
83
-            esc_html__('Starting Datetime Offset Fix', 'event_espresso')
84
-        );
85
-    }
86
-
87
-    /**
88
-     * Performs another step of the job
89
-     *
90
-     * @param JobParameters $job_parameters
91
-     * @param int           $batch_size
92
-     * @return JobStepResponse
93
-     * @throws EE_Error
94
-     * @throws InvalidArgumentException
95
-     * @throws InvalidDataTypeException
96
-     * @throws InvalidInterfaceException
97
-     */
98
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
-    {
100
-        $models_to_process = $this->getModelsWithDatetimeFields();
101
-        // let's pop off the a model and do the query to apply the offset.
102
-        $model_to_process = array_pop($models_to_process);
103
-        // update our record
104
-        $this->setModelsToProcess($models_to_process);
105
-        $this->processModel($model_to_process);
106
-        $this->updateCountOfModelsProcessed();
107
-        $job_parameters->set_units_processed($this->getCountOfModelsProcessed());
108
-        if (count($models_to_process) > 0) {
109
-            $job_parameters->set_status(JobParameters::status_continue);
110
-        } else {
111
-            $job_parameters->set_status(JobParameters::status_complete);
112
-        }
113
-        return new JobStepResponse(
114
-            $job_parameters,
115
-            sprintf(
116
-                esc_html__('Updated the offset for all datetime fields on the %s model.', 'event_espresso'),
117
-                $model_to_process
118
-            )
119
-        );
120
-    }
121
-
122
-    /**
123
-     * Performs any clean-up logic when we know the job is completed
124
-     *
125
-     * @param JobParameters $job_parameters
126
-     * @return JobStepResponse
127
-     * @throws BatchRequestException
128
-     */
129
-    public function cleanup_job(JobParameters $job_parameters)
130
-    {
131
-        // delete important saved options.
132
-        delete_option(self::MODELS_TO_PROCESS_OPTION_KEY);
133
-        delete_option(self::COUNT_OF_MODELS_PROCESSED);
134
-        delete_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE);
135
-        delete_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE);
136
-        return new JobStepResponse($job_parameters, esc_html__(
137
-            'Offset has been applied to all affected fields.',
138
-            'event_espresso'
139
-        ));
140
-    }
141
-
142
-
143
-    /**
144
-     * Contains the logic for processing a model and applying the datetime offset to affected fields on that model.
145
-     *
146
-     * @param string $model_class_name
147
-     * @throws EE_Error
148
-     */
149
-    protected function processModel($model_class_name)
150
-    {
151
-        global $wpdb;
152
-        /** @var EEM_Base $model */
153
-        $model = $model_class_name::instance();
154
-        $original_offset = self::getOffset();
155
-        $start_date_range = self::getStartDateRange();
156
-        $end_date_range = self::getEndDateRange();
157
-        $sql_date_function = $original_offset > 0 ? 'DATE_ADD' : 'DATE_SUB';
158
-        $offset = abs($original_offset) * 60;
159
-        $date_ranges = array();
160
-        // since some affected models might have two tables, we have to get our tables and set up a query for each table.
161
-        foreach ($model->get_tables() as $table) {
162
-            $query = 'UPDATE ' . $table->get_table_name();
163
-            $fields_affected = array();
164
-            $inner_query = array();
165
-            foreach ($model->_get_fields_for_table($table->get_table_alias()) as $model_field) {
166
-                if ($model_field instanceof EE_Datetime_Field) {
167
-                    $inner_query[$model_field->get_table_column()] = $model_field->get_table_column() . ' = '
168
-                                                                     . $sql_date_function . '('
169
-                                                                     . $model_field->get_table_column()
170
-                                                                     . ", INTERVAL {$offset} MINUTE)";
171
-                    $fields_affected[] = $model_field;
172
-                }
173
-            }
174
-            if (! $fields_affected) {
175
-                continue;
176
-            }
177
-            // do we do one query per column/field or one query for all fields on the model? It all depends on whether
178
-            // there is a date range applied or not.
179
-            if ($start_date_range instanceof DbSafeDateTime || $end_date_range instanceof DbSafeDateTime) {
180
-                $result = $this->doQueryForEachField($query, $inner_query, $start_date_range, $end_date_range);
181
-            } else {
182
-                $result = $this->doQueryForAllFields($query, $inner_query);
183
-            }
184
-
185
-            // record appropriate logs for the query
186
-            switch (true) {
187
-                case $result === false:
188
-                    // record error.
189
-                    $error_message = $wpdb->last_error;
190
-                    // handle the edgecases where last_error might be empty.
191
-                    if (! $error_message) {
192
-                        $error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
193
-                    }
194
-                    $this->recordChangeLog($model, $original_offset, $table, $fields_affected, $error_message);
195
-                    break;
196
-                case is_array($result) && ! empty($result):
197
-                    foreach ($result as $field_name => $error_message) {
198
-                        $this->recordChangeLog($model, $original_offset, $table, array($field_name), $error_message);
199
-                    }
200
-                    break;
201
-                default:
202
-                    $this->recordChangeLog($model, $original_offset, $table, $fields_affected);
203
-            }
204
-        }
205
-    }
206
-
207
-
208
-    /**
209
-     * Does the query on each $inner_query individually.
210
-     *
211
-     * @param string              $query
212
-     * @param array               $inner_query
213
-     * @param DbSafeDateTime|null $start_date_range
214
-     * @param DbSafeDateTime|null $end_date_range
215
-     * @return array  An array of any errors encountered and the fields they were for.
216
-     */
217
-    private function doQueryForEachField($query, array $inner_query, $start_date_range, $end_date_range)
218
-    {
219
-        global $wpdb;
220
-        $errors = array();
221
-        foreach ($inner_query as $field_name => $field_query) {
222
-            $query_to_run = $query;
223
-            $where_conditions = array();
224
-            $query_to_run .= ' SET ' . $field_query;
225
-            if ($start_date_range instanceof DbSafeDateTime) {
226
-                $start_date = $start_date_range->format(EE_Datetime_Field::mysql_timestamp_format);
227
-                $where_conditions[] = "{$field_name} > '{$start_date}'";
228
-            }
229
-            if ($end_date_range instanceof DbSafeDateTime) {
230
-                $end_date = $end_date_range->format(EE_Datetime_Field::mysql_timestamp_format);
231
-                $where_conditions[] = "{$field_name} < '{$end_date}'";
232
-            }
233
-            if ($where_conditions) {
234
-                $query_to_run .= ' WHERE ' . implode(' AND ', $where_conditions);
235
-            }
236
-            $result = $wpdb->query($query_to_run);
237
-            if ($result === false) {
238
-                // record error.
239
-                $error_message = $wpdb->last_error;
240
-                // handle the edgecases where last_error might be empty.
241
-                if (! $error_message) {
242
-                    $error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
243
-                }
244
-                $errors[$field_name] = $error_message;
245
-            }
246
-        }
247
-        return $errors;
248
-    }
249
-
250
-
251
-    /**
252
-     * Performs the query for all fields within the inner_query
253
-     *
254
-     * @param string $query
255
-     * @param array  $inner_query
256
-     * @return false|int
257
-     */
258
-    private function doQueryForAllFields($query, array $inner_query)
259
-    {
260
-        global $wpdb;
261
-        $query .= ' SET ' . implode(',', $inner_query);
262
-        return $wpdb->query($query);
263
-    }
264
-
265
-
266
-    /**
267
-     * Records a changelog entry using the given information.
268
-     *
269
-     * @param EEM_Base              $model
270
-     * @param float                 $offset
271
-     * @param EE_Table_Base         $table
272
-     * @param EE_Model_Field_Base[] $model_fields_affected
273
-     * @param string                $error_message If present then there was an error so let's record that instead.
274
-     * @throws EE_Error
275
-     */
276
-    private function recordChangeLog(
277
-        EEM_Base $model,
278
-        $offset,
279
-        EE_Table_Base $table,
280
-        $model_fields_affected,
281
-        $error_message = ''
282
-    ) {
283
-        // setup $fields list.
284
-        $fields = array();
285
-        /** @var EE_Datetime_Field $model_field */
286
-        foreach ($model_fields_affected as $model_field) {
287
-            if (! $model_field instanceof EE_Datetime_Field) {
288
-                continue;
289
-            }
290
-            $fields[] = $model_field->get_name();
291
-        }
292
-        // setup the message for the changelog entry.
293
-        $message = $error_message
294
-            ? sprintf(
295
-                esc_html__(
296
-                    'The %1$s table for the %2$s model did not have the offset of %3$f applied to its fields (%4$s), because of the following error:%5$s',
297
-                    'event_espresso'
298
-                ),
299
-                $table->get_table_name(),
300
-                $model->get_this_model_name(),
301
-                $offset,
302
-                implode(',', $fields),
303
-                $error_message
304
-            )
305
-            : sprintf(
306
-                esc_html__(
307
-                    'The %1$s table for the %2$s model has had the offset of %3$f applied to its following fields: %4$s',
308
-                    'event_espresso'
309
-                ),
310
-                $table->get_table_name(),
311
-                $model->get_this_model_name(),
312
-                $offset,
313
-                implode(',', $fields)
314
-            );
315
-        // write to the log
316
-        $changelog = EE_Change_Log::new_instance(array(
317
-            'LOG_type'    => $error_message
318
-                ? self::DATETIME_OFFSET_FIX_CHANGELOG_ERROR_TYPE
319
-                : self::DATETIME_OFFSET_FIX_CHANGELOG_TYPE,
320
-            'LOG_message' => $message,
321
-        ));
322
-        $changelog->save();
323
-    }
324
-
325
-
326
-    /**
327
-     * Returns an array of models that have datetime fields.
328
-     * This array is added to a short lived transient cache to keep having to build this list to a minimum.
329
-     *
330
-     * @return array an array of model class names.
331
-     * @throws EE_Error
332
-     * @throws InvalidDataTypeException
333
-     * @throws InvalidInterfaceException
334
-     * @throws InvalidArgumentException
335
-     */
336
-    private function getModelsWithDatetimeFields()
337
-    {
338
-        $this->getModelsToProcess();
339
-        if (! empty($this->models_with_datetime_fields)) {
340
-            return $this->models_with_datetime_fields;
341
-        }
342
-
343
-        $all_non_abstract_models = EE_Registry::instance()->non_abstract_db_models;
344
-        foreach ($all_non_abstract_models as $non_abstract_model) {
345
-            // get model instance
346
-            /** @var EEM_Base $non_abstract_model */
347
-            $non_abstract_model = $non_abstract_model::instance();
348
-            if ($non_abstract_model->get_a_field_of_type('EE_Datetime_Field') instanceof EE_Datetime_Field) {
349
-                $this->models_with_datetime_fields[] = get_class($non_abstract_model);
350
-            }
351
-        }
352
-        $this->setModelsToProcess($this->models_with_datetime_fields);
353
-        return $this->models_with_datetime_fields;
354
-    }
355
-
356
-
357
-    /**
358
-     * This simply records the models that have been processed with our tracking option.
359
-     *
360
-     * @param array $models_to_set array of model class names.
361
-     */
362
-    private function setModelsToProcess($models_to_set)
363
-    {
364
-        update_option(self::MODELS_TO_PROCESS_OPTION_KEY, $models_to_set);
365
-    }
366
-
367
-
368
-    /**
369
-     * Used to keep track of how many models have been processed for the batch
370
-     *
371
-     * @param $count
372
-     */
373
-    private function updateCountOfModelsProcessed($count = 1)
374
-    {
375
-        $count = $this->getCountOfModelsProcessed() + (int)$count;
376
-        update_option(self::COUNT_OF_MODELS_PROCESSED, $count);
377
-    }
378
-
379
-
380
-    /**
381
-     * Retrieve the tracked number of models processed between requests.
382
-     *
383
-     * @return int
384
-     */
385
-    private function getCountOfModelsProcessed()
386
-    {
387
-        return (int)get_option(self::COUNT_OF_MODELS_PROCESSED, 0);
388
-    }
389
-
390
-
391
-    /**
392
-     * Returns the models that are left to process.
393
-     *
394
-     * @return array  an array of model class names.
395
-     */
396
-    private function getModelsToProcess()
397
-    {
398
-        if (empty($this->models_with_datetime_fields)) {
399
-            $this->models_with_datetime_fields = get_option(self::MODELS_TO_PROCESS_OPTION_KEY, array());
400
-        }
401
-        return $this->models_with_datetime_fields;
402
-    }
403
-
404
-
405
-    /**
406
-     * Used to record the offset that will be applied to dates and times for EE_Datetime_Field columns.
407
-     *
408
-     * @param float $offset
409
-     */
410
-    public static function updateOffset($offset)
411
-    {
412
-        update_option(self::OFFSET_TO_APPLY_OPTION_KEY, $offset);
413
-    }
414
-
415
-
416
-    /**
417
-     * Used to retrieve the saved offset that will be applied to dates and times for EE_Datetime_Field columns.
418
-     *
419
-     * @return float
420
-     */
421
-    public static function getOffset()
422
-    {
423
-        return (float)get_option(self::OFFSET_TO_APPLY_OPTION_KEY, 0);
424
-    }
425
-
426
-
427
-    /**
428
-     * Used to set the saved offset range start date.
429
-     *
430
-     * @param DbSafeDateTime|null $start_date
431
-     */
432
-    public static function updateStartDateRange(DbSafeDateTime $start_date = null)
433
-    {
434
-        $date_to_save = $start_date instanceof DbSafeDateTime
435
-            ? $start_date->format('U')
436
-            : '';
437
-        update_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE, $date_to_save);
438
-    }
439
-
440
-
441
-    /**
442
-     * Used to get the saved offset range start date.
443
-     *
444
-     * @return DbSafeDateTime|null
445
-     */
446
-    public static function getStartDateRange()
447
-    {
448
-        $start_date = get_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE, null);
449
-        try {
450
-            $datetime = DateTime::createFromFormat('U', $start_date, new DateTimeZone('UTC'));
451
-            $start_date = $datetime instanceof DateTime
452
-                ? DbSafeDateTime::createFromDateTime($datetime)
453
-                : null;
454
-        } catch (Exception $e) {
455
-            $start_date = null;
456
-        }
457
-        return $start_date;
458
-    }
459
-
460
-
461
-    /**
462
-     * Used to set the saved offset range end date.
463
-     *
464
-     * @param DbSafeDateTime|null $end_date
465
-     */
466
-    public static function updateEndDateRange(DbSafeDateTime $end_date = null)
467
-    {
468
-        $date_to_save = $end_date instanceof DbSafeDateTime
469
-            ? $end_date->format('U')
470
-            : '';
471
-        update_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE, $date_to_save);
472
-    }
473
-
474
-
475
-    /**
476
-     * Used to get the saved offset range end date.
477
-     *
478
-     * @return DbSafeDateTime|null
479
-     */
480
-    public static function getEndDateRange()
481
-    {
482
-        $end_date = get_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE, null);
483
-        try {
484
-            $datetime = DateTime::createFromFormat('U', $end_date, new DateTimeZone('UTC'));
485
-            $end_date = $datetime instanceof Datetime
486
-                ? DbSafeDateTime::createFromDateTime($datetime)
487
-                : null;
488
-        } catch (Exception $e) {
489
-            $end_date = null;
490
-        }
491
-        return $end_date;
492
-    }
27
+	/**
28
+	 * Key for the option used to track which models have been processed when doing the batches.
29
+	 */
30
+	const MODELS_TO_PROCESS_OPTION_KEY = 'ee_models_processed_for_datetime_offset_fix';
31
+
32
+
33
+	const COUNT_OF_MODELS_PROCESSED = 'ee_count_of_ee_models_processed_for_datetime_offset_fixed';
34
+
35
+	/**
36
+	 * Key for the option used to track what the current offset is that will be applied when this tool is executed.
37
+	 */
38
+	const OFFSET_TO_APPLY_OPTION_KEY = 'ee_datetime_offset_fix_offset_to_apply';
39
+
40
+
41
+	const OPTION_KEY_OFFSET_RANGE_START_DATE = 'ee_datetime_offset_start_date_range';
42
+
43
+
44
+	const OPTION_KEY_OFFSET_RANGE_END_DATE = 'ee_datetime_offset_end_date_range';
45
+
46
+
47
+	/**
48
+	 * String labelling the datetime offset fix type for change-log entries.
49
+	 */
50
+	const DATETIME_OFFSET_FIX_CHANGELOG_TYPE = 'datetime_offset_fix';
51
+
52
+
53
+	/**
54
+	 * String labelling a datetime offset fix error for change-log entries.
55
+	 */
56
+	const DATETIME_OFFSET_FIX_CHANGELOG_ERROR_TYPE = 'datetime_offset_fix_error';
57
+
58
+	/**
59
+	 * @var EEM_Base[]
60
+	 */
61
+	protected $models_with_datetime_fields = array();
62
+
63
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
64
+	/**
65
+	 * Performs any necessary setup for starting the job. This is also a good
66
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
67
+	 * when continue_job will be called
68
+	 *
69
+	 * @param JobParameters $job_parameters
70
+	 * @return JobStepResponse
71
+	 * @throws EE_Error
72
+	 * @throws InvalidArgumentException
73
+	 * @throws InvalidDataTypeException
74
+	 * @throws InvalidInterfaceException
75
+	 */
76
+	public function create_job(JobParameters $job_parameters)
77
+	{
78
+		$models_with_datetime_fields = $this->getModelsWithDatetimeFields();
79
+		// we'll be doing each model as a batch.
80
+		$job_parameters->set_job_size(count($models_with_datetime_fields));
81
+		return new JobStepResponse(
82
+			$job_parameters,
83
+			esc_html__('Starting Datetime Offset Fix', 'event_espresso')
84
+		);
85
+	}
86
+
87
+	/**
88
+	 * Performs another step of the job
89
+	 *
90
+	 * @param JobParameters $job_parameters
91
+	 * @param int           $batch_size
92
+	 * @return JobStepResponse
93
+	 * @throws EE_Error
94
+	 * @throws InvalidArgumentException
95
+	 * @throws InvalidDataTypeException
96
+	 * @throws InvalidInterfaceException
97
+	 */
98
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
+	{
100
+		$models_to_process = $this->getModelsWithDatetimeFields();
101
+		// let's pop off the a model and do the query to apply the offset.
102
+		$model_to_process = array_pop($models_to_process);
103
+		// update our record
104
+		$this->setModelsToProcess($models_to_process);
105
+		$this->processModel($model_to_process);
106
+		$this->updateCountOfModelsProcessed();
107
+		$job_parameters->set_units_processed($this->getCountOfModelsProcessed());
108
+		if (count($models_to_process) > 0) {
109
+			$job_parameters->set_status(JobParameters::status_continue);
110
+		} else {
111
+			$job_parameters->set_status(JobParameters::status_complete);
112
+		}
113
+		return new JobStepResponse(
114
+			$job_parameters,
115
+			sprintf(
116
+				esc_html__('Updated the offset for all datetime fields on the %s model.', 'event_espresso'),
117
+				$model_to_process
118
+			)
119
+		);
120
+	}
121
+
122
+	/**
123
+	 * Performs any clean-up logic when we know the job is completed
124
+	 *
125
+	 * @param JobParameters $job_parameters
126
+	 * @return JobStepResponse
127
+	 * @throws BatchRequestException
128
+	 */
129
+	public function cleanup_job(JobParameters $job_parameters)
130
+	{
131
+		// delete important saved options.
132
+		delete_option(self::MODELS_TO_PROCESS_OPTION_KEY);
133
+		delete_option(self::COUNT_OF_MODELS_PROCESSED);
134
+		delete_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE);
135
+		delete_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE);
136
+		return new JobStepResponse($job_parameters, esc_html__(
137
+			'Offset has been applied to all affected fields.',
138
+			'event_espresso'
139
+		));
140
+	}
141
+
142
+
143
+	/**
144
+	 * Contains the logic for processing a model and applying the datetime offset to affected fields on that model.
145
+	 *
146
+	 * @param string $model_class_name
147
+	 * @throws EE_Error
148
+	 */
149
+	protected function processModel($model_class_name)
150
+	{
151
+		global $wpdb;
152
+		/** @var EEM_Base $model */
153
+		$model = $model_class_name::instance();
154
+		$original_offset = self::getOffset();
155
+		$start_date_range = self::getStartDateRange();
156
+		$end_date_range = self::getEndDateRange();
157
+		$sql_date_function = $original_offset > 0 ? 'DATE_ADD' : 'DATE_SUB';
158
+		$offset = abs($original_offset) * 60;
159
+		$date_ranges = array();
160
+		// since some affected models might have two tables, we have to get our tables and set up a query for each table.
161
+		foreach ($model->get_tables() as $table) {
162
+			$query = 'UPDATE ' . $table->get_table_name();
163
+			$fields_affected = array();
164
+			$inner_query = array();
165
+			foreach ($model->_get_fields_for_table($table->get_table_alias()) as $model_field) {
166
+				if ($model_field instanceof EE_Datetime_Field) {
167
+					$inner_query[$model_field->get_table_column()] = $model_field->get_table_column() . ' = '
168
+																	 . $sql_date_function . '('
169
+																	 . $model_field->get_table_column()
170
+																	 . ", INTERVAL {$offset} MINUTE)";
171
+					$fields_affected[] = $model_field;
172
+				}
173
+			}
174
+			if (! $fields_affected) {
175
+				continue;
176
+			}
177
+			// do we do one query per column/field or one query for all fields on the model? It all depends on whether
178
+			// there is a date range applied or not.
179
+			if ($start_date_range instanceof DbSafeDateTime || $end_date_range instanceof DbSafeDateTime) {
180
+				$result = $this->doQueryForEachField($query, $inner_query, $start_date_range, $end_date_range);
181
+			} else {
182
+				$result = $this->doQueryForAllFields($query, $inner_query);
183
+			}
184
+
185
+			// record appropriate logs for the query
186
+			switch (true) {
187
+				case $result === false:
188
+					// record error.
189
+					$error_message = $wpdb->last_error;
190
+					// handle the edgecases where last_error might be empty.
191
+					if (! $error_message) {
192
+						$error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
193
+					}
194
+					$this->recordChangeLog($model, $original_offset, $table, $fields_affected, $error_message);
195
+					break;
196
+				case is_array($result) && ! empty($result):
197
+					foreach ($result as $field_name => $error_message) {
198
+						$this->recordChangeLog($model, $original_offset, $table, array($field_name), $error_message);
199
+					}
200
+					break;
201
+				default:
202
+					$this->recordChangeLog($model, $original_offset, $table, $fields_affected);
203
+			}
204
+		}
205
+	}
206
+
207
+
208
+	/**
209
+	 * Does the query on each $inner_query individually.
210
+	 *
211
+	 * @param string              $query
212
+	 * @param array               $inner_query
213
+	 * @param DbSafeDateTime|null $start_date_range
214
+	 * @param DbSafeDateTime|null $end_date_range
215
+	 * @return array  An array of any errors encountered and the fields they were for.
216
+	 */
217
+	private function doQueryForEachField($query, array $inner_query, $start_date_range, $end_date_range)
218
+	{
219
+		global $wpdb;
220
+		$errors = array();
221
+		foreach ($inner_query as $field_name => $field_query) {
222
+			$query_to_run = $query;
223
+			$where_conditions = array();
224
+			$query_to_run .= ' SET ' . $field_query;
225
+			if ($start_date_range instanceof DbSafeDateTime) {
226
+				$start_date = $start_date_range->format(EE_Datetime_Field::mysql_timestamp_format);
227
+				$where_conditions[] = "{$field_name} > '{$start_date}'";
228
+			}
229
+			if ($end_date_range instanceof DbSafeDateTime) {
230
+				$end_date = $end_date_range->format(EE_Datetime_Field::mysql_timestamp_format);
231
+				$where_conditions[] = "{$field_name} < '{$end_date}'";
232
+			}
233
+			if ($where_conditions) {
234
+				$query_to_run .= ' WHERE ' . implode(' AND ', $where_conditions);
235
+			}
236
+			$result = $wpdb->query($query_to_run);
237
+			if ($result === false) {
238
+				// record error.
239
+				$error_message = $wpdb->last_error;
240
+				// handle the edgecases where last_error might be empty.
241
+				if (! $error_message) {
242
+					$error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
243
+				}
244
+				$errors[$field_name] = $error_message;
245
+			}
246
+		}
247
+		return $errors;
248
+	}
249
+
250
+
251
+	/**
252
+	 * Performs the query for all fields within the inner_query
253
+	 *
254
+	 * @param string $query
255
+	 * @param array  $inner_query
256
+	 * @return false|int
257
+	 */
258
+	private function doQueryForAllFields($query, array $inner_query)
259
+	{
260
+		global $wpdb;
261
+		$query .= ' SET ' . implode(',', $inner_query);
262
+		return $wpdb->query($query);
263
+	}
264
+
265
+
266
+	/**
267
+	 * Records a changelog entry using the given information.
268
+	 *
269
+	 * @param EEM_Base              $model
270
+	 * @param float                 $offset
271
+	 * @param EE_Table_Base         $table
272
+	 * @param EE_Model_Field_Base[] $model_fields_affected
273
+	 * @param string                $error_message If present then there was an error so let's record that instead.
274
+	 * @throws EE_Error
275
+	 */
276
+	private function recordChangeLog(
277
+		EEM_Base $model,
278
+		$offset,
279
+		EE_Table_Base $table,
280
+		$model_fields_affected,
281
+		$error_message = ''
282
+	) {
283
+		// setup $fields list.
284
+		$fields = array();
285
+		/** @var EE_Datetime_Field $model_field */
286
+		foreach ($model_fields_affected as $model_field) {
287
+			if (! $model_field instanceof EE_Datetime_Field) {
288
+				continue;
289
+			}
290
+			$fields[] = $model_field->get_name();
291
+		}
292
+		// setup the message for the changelog entry.
293
+		$message = $error_message
294
+			? sprintf(
295
+				esc_html__(
296
+					'The %1$s table for the %2$s model did not have the offset of %3$f applied to its fields (%4$s), because of the following error:%5$s',
297
+					'event_espresso'
298
+				),
299
+				$table->get_table_name(),
300
+				$model->get_this_model_name(),
301
+				$offset,
302
+				implode(',', $fields),
303
+				$error_message
304
+			)
305
+			: sprintf(
306
+				esc_html__(
307
+					'The %1$s table for the %2$s model has had the offset of %3$f applied to its following fields: %4$s',
308
+					'event_espresso'
309
+				),
310
+				$table->get_table_name(),
311
+				$model->get_this_model_name(),
312
+				$offset,
313
+				implode(',', $fields)
314
+			);
315
+		// write to the log
316
+		$changelog = EE_Change_Log::new_instance(array(
317
+			'LOG_type'    => $error_message
318
+				? self::DATETIME_OFFSET_FIX_CHANGELOG_ERROR_TYPE
319
+				: self::DATETIME_OFFSET_FIX_CHANGELOG_TYPE,
320
+			'LOG_message' => $message,
321
+		));
322
+		$changelog->save();
323
+	}
324
+
325
+
326
+	/**
327
+	 * Returns an array of models that have datetime fields.
328
+	 * This array is added to a short lived transient cache to keep having to build this list to a minimum.
329
+	 *
330
+	 * @return array an array of model class names.
331
+	 * @throws EE_Error
332
+	 * @throws InvalidDataTypeException
333
+	 * @throws InvalidInterfaceException
334
+	 * @throws InvalidArgumentException
335
+	 */
336
+	private function getModelsWithDatetimeFields()
337
+	{
338
+		$this->getModelsToProcess();
339
+		if (! empty($this->models_with_datetime_fields)) {
340
+			return $this->models_with_datetime_fields;
341
+		}
342
+
343
+		$all_non_abstract_models = EE_Registry::instance()->non_abstract_db_models;
344
+		foreach ($all_non_abstract_models as $non_abstract_model) {
345
+			// get model instance
346
+			/** @var EEM_Base $non_abstract_model */
347
+			$non_abstract_model = $non_abstract_model::instance();
348
+			if ($non_abstract_model->get_a_field_of_type('EE_Datetime_Field') instanceof EE_Datetime_Field) {
349
+				$this->models_with_datetime_fields[] = get_class($non_abstract_model);
350
+			}
351
+		}
352
+		$this->setModelsToProcess($this->models_with_datetime_fields);
353
+		return $this->models_with_datetime_fields;
354
+	}
355
+
356
+
357
+	/**
358
+	 * This simply records the models that have been processed with our tracking option.
359
+	 *
360
+	 * @param array $models_to_set array of model class names.
361
+	 */
362
+	private function setModelsToProcess($models_to_set)
363
+	{
364
+		update_option(self::MODELS_TO_PROCESS_OPTION_KEY, $models_to_set);
365
+	}
366
+
367
+
368
+	/**
369
+	 * Used to keep track of how many models have been processed for the batch
370
+	 *
371
+	 * @param $count
372
+	 */
373
+	private function updateCountOfModelsProcessed($count = 1)
374
+	{
375
+		$count = $this->getCountOfModelsProcessed() + (int)$count;
376
+		update_option(self::COUNT_OF_MODELS_PROCESSED, $count);
377
+	}
378
+
379
+
380
+	/**
381
+	 * Retrieve the tracked number of models processed between requests.
382
+	 *
383
+	 * @return int
384
+	 */
385
+	private function getCountOfModelsProcessed()
386
+	{
387
+		return (int)get_option(self::COUNT_OF_MODELS_PROCESSED, 0);
388
+	}
389
+
390
+
391
+	/**
392
+	 * Returns the models that are left to process.
393
+	 *
394
+	 * @return array  an array of model class names.
395
+	 */
396
+	private function getModelsToProcess()
397
+	{
398
+		if (empty($this->models_with_datetime_fields)) {
399
+			$this->models_with_datetime_fields = get_option(self::MODELS_TO_PROCESS_OPTION_KEY, array());
400
+		}
401
+		return $this->models_with_datetime_fields;
402
+	}
403
+
404
+
405
+	/**
406
+	 * Used to record the offset that will be applied to dates and times for EE_Datetime_Field columns.
407
+	 *
408
+	 * @param float $offset
409
+	 */
410
+	public static function updateOffset($offset)
411
+	{
412
+		update_option(self::OFFSET_TO_APPLY_OPTION_KEY, $offset);
413
+	}
414
+
415
+
416
+	/**
417
+	 * Used to retrieve the saved offset that will be applied to dates and times for EE_Datetime_Field columns.
418
+	 *
419
+	 * @return float
420
+	 */
421
+	public static function getOffset()
422
+	{
423
+		return (float)get_option(self::OFFSET_TO_APPLY_OPTION_KEY, 0);
424
+	}
425
+
426
+
427
+	/**
428
+	 * Used to set the saved offset range start date.
429
+	 *
430
+	 * @param DbSafeDateTime|null $start_date
431
+	 */
432
+	public static function updateStartDateRange(DbSafeDateTime $start_date = null)
433
+	{
434
+		$date_to_save = $start_date instanceof DbSafeDateTime
435
+			? $start_date->format('U')
436
+			: '';
437
+		update_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE, $date_to_save);
438
+	}
439
+
440
+
441
+	/**
442
+	 * Used to get the saved offset range start date.
443
+	 *
444
+	 * @return DbSafeDateTime|null
445
+	 */
446
+	public static function getStartDateRange()
447
+	{
448
+		$start_date = get_option(self::OPTION_KEY_OFFSET_RANGE_START_DATE, null);
449
+		try {
450
+			$datetime = DateTime::createFromFormat('U', $start_date, new DateTimeZone('UTC'));
451
+			$start_date = $datetime instanceof DateTime
452
+				? DbSafeDateTime::createFromDateTime($datetime)
453
+				: null;
454
+		} catch (Exception $e) {
455
+			$start_date = null;
456
+		}
457
+		return $start_date;
458
+	}
459
+
460
+
461
+	/**
462
+	 * Used to set the saved offset range end date.
463
+	 *
464
+	 * @param DbSafeDateTime|null $end_date
465
+	 */
466
+	public static function updateEndDateRange(DbSafeDateTime $end_date = null)
467
+	{
468
+		$date_to_save = $end_date instanceof DbSafeDateTime
469
+			? $end_date->format('U')
470
+			: '';
471
+		update_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE, $date_to_save);
472
+	}
473
+
474
+
475
+	/**
476
+	 * Used to get the saved offset range end date.
477
+	 *
478
+	 * @return DbSafeDateTime|null
479
+	 */
480
+	public static function getEndDateRange()
481
+	{
482
+		$end_date = get_option(self::OPTION_KEY_OFFSET_RANGE_END_DATE, null);
483
+		try {
484
+			$datetime = DateTime::createFromFormat('U', $end_date, new DateTimeZone('UTC'));
485
+			$end_date = $datetime instanceof Datetime
486
+				? DbSafeDateTime::createFromDateTime($datetime)
487
+				: null;
488
+		} catch (Exception $e) {
489
+			$end_date = null;
490
+		}
491
+		return $end_date;
492
+	}
493 493
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -159,19 +159,19 @@  discard block
 block discarded – undo
159 159
         $date_ranges = array();
160 160
         // since some affected models might have two tables, we have to get our tables and set up a query for each table.
161 161
         foreach ($model->get_tables() as $table) {
162
-            $query = 'UPDATE ' . $table->get_table_name();
162
+            $query = 'UPDATE '.$table->get_table_name();
163 163
             $fields_affected = array();
164 164
             $inner_query = array();
165 165
             foreach ($model->_get_fields_for_table($table->get_table_alias()) as $model_field) {
166 166
                 if ($model_field instanceof EE_Datetime_Field) {
167
-                    $inner_query[$model_field->get_table_column()] = $model_field->get_table_column() . ' = '
168
-                                                                     . $sql_date_function . '('
167
+                    $inner_query[$model_field->get_table_column()] = $model_field->get_table_column().' = '
168
+                                                                     . $sql_date_function.'('
169 169
                                                                      . $model_field->get_table_column()
170 170
                                                                      . ", INTERVAL {$offset} MINUTE)";
171 171
                     $fields_affected[] = $model_field;
172 172
                 }
173 173
             }
174
-            if (! $fields_affected) {
174
+            if ( ! $fields_affected) {
175 175
                 continue;
176 176
             }
177 177
             // do we do one query per column/field or one query for all fields on the model? It all depends on whether
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
                     // record error.
189 189
                     $error_message = $wpdb->last_error;
190 190
                     // handle the edgecases where last_error might be empty.
191
-                    if (! $error_message) {
191
+                    if ( ! $error_message) {
192 192
                         $error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
193 193
                     }
194 194
                     $this->recordChangeLog($model, $original_offset, $table, $fields_affected, $error_message);
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
         foreach ($inner_query as $field_name => $field_query) {
222 222
             $query_to_run = $query;
223 223
             $where_conditions = array();
224
-            $query_to_run .= ' SET ' . $field_query;
224
+            $query_to_run .= ' SET '.$field_query;
225 225
             if ($start_date_range instanceof DbSafeDateTime) {
226 226
                 $start_date = $start_date_range->format(EE_Datetime_Field::mysql_timestamp_format);
227 227
                 $where_conditions[] = "{$field_name} > '{$start_date}'";
@@ -231,14 +231,14 @@  discard block
 block discarded – undo
231 231
                 $where_conditions[] = "{$field_name} < '{$end_date}'";
232 232
             }
233 233
             if ($where_conditions) {
234
-                $query_to_run .= ' WHERE ' . implode(' AND ', $where_conditions);
234
+                $query_to_run .= ' WHERE '.implode(' AND ', $where_conditions);
235 235
             }
236 236
             $result = $wpdb->query($query_to_run);
237 237
             if ($result === false) {
238 238
                 // record error.
239 239
                 $error_message = $wpdb->last_error;
240 240
                 // handle the edgecases where last_error might be empty.
241
-                if (! $error_message) {
241
+                if ( ! $error_message) {
242 242
                     $error_message = esc_html__('Unknown mysql error occured.', 'event_espresso');
243 243
                 }
244 244
                 $errors[$field_name] = $error_message;
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
     private function doQueryForAllFields($query, array $inner_query)
259 259
     {
260 260
         global $wpdb;
261
-        $query .= ' SET ' . implode(',', $inner_query);
261
+        $query .= ' SET '.implode(',', $inner_query);
262 262
         return $wpdb->query($query);
263 263
     }
264 264
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
         $fields = array();
285 285
         /** @var EE_Datetime_Field $model_field */
286 286
         foreach ($model_fields_affected as $model_field) {
287
-            if (! $model_field instanceof EE_Datetime_Field) {
287
+            if ( ! $model_field instanceof EE_Datetime_Field) {
288 288
                 continue;
289 289
             }
290 290
             $fields[] = $model_field->get_name();
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
     private function getModelsWithDatetimeFields()
337 337
     {
338 338
         $this->getModelsToProcess();
339
-        if (! empty($this->models_with_datetime_fields)) {
339
+        if ( ! empty($this->models_with_datetime_fields)) {
340 340
             return $this->models_with_datetime_fields;
341 341
         }
342 342
 
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
      */
373 373
     private function updateCountOfModelsProcessed($count = 1)
374 374
     {
375
-        $count = $this->getCountOfModelsProcessed() + (int)$count;
375
+        $count = $this->getCountOfModelsProcessed() + (int) $count;
376 376
         update_option(self::COUNT_OF_MODELS_PROCESSED, $count);
377 377
     }
378 378
 
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
      */
385 385
     private function getCountOfModelsProcessed()
386 386
     {
387
-        return (int)get_option(self::COUNT_OF_MODELS_PROCESSED, 0);
387
+        return (int) get_option(self::COUNT_OF_MODELS_PROCESSED, 0);
388 388
     }
389 389
 
390 390
 
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
      */
421 421
     public static function getOffset()
422 422
     {
423
-        return (float)get_option(self::OFFSET_TO_APPLY_OPTION_KEY, 0);
423
+        return (float) get_option(self::OFFSET_TO_APPLY_OPTION_KEY, 0);
424 424
     }
425 425
 
426 426
 
Please login to merge, or discard this patch.