Completed
Branch BETA-4.9-message-activity (c2a8e0)
by
unknown
18:28 queued 10s
created

RegistrationsReport::continue_job()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 20

Duplication

Lines 4
Ratio 17.39 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 4
loc 23
rs 9.0856
cc 2
eloc 20
nc 2
nop 2
1
<?php
2
/**
3
 *
4
 * Class RegistrationsReport
5
 *
6
 * Generates the registrations report for the specified event,
7
 * or for all events
8
 *
9
 * @package         Event Espresso
10
 * @subpackage    batch
11
 * @author				Mike Nelson
12
 * @since		 	   4.8.26
13
 *
14
 */
15
namespace EventEspressoBatchRequest\JobHandlers;
16
17
use EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile;
18
use EventEspressoBatchRequest\Helpers\BatchRequestException;
19
use EventEspressoBatchRequest\Helpers\JobParameters;
20
use EventEspressoBatchRequest\Helpers\JobStepResponse;
21
22
if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
23
	exit( 'No direct script access allowed' );
24
}
25
26
27
28
class RegistrationsReport extends JobHandlerFile {
29
30
	/**
31
	 * Performs any necessary setup for starting the job. This is also a good
32
	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
33
	 * when continue_job will be called
34
	 * @param JobParameters $job_parameters
35
	 * @throws BatchRequestException
36
	 * @return JobStepResponse
37
	 */
38
	public function create_job( JobParameters $job_parameters ) {
39
		$event_id = intval( $job_parameters->request_datum( 'EVT_ID', '0' ) );
40
		if( ! \EE_Capabilities::instance()->current_user_can( 'ee_read_registrations', 'generating_report' ) ) {
41
			throw new BatchRequestException(
42
				__( 'You do not have permission to view registrations', 'event_espresso')
43
			);
44
		}
45
		$filepath = $this->create_file_from_job_with_name(
46
			$job_parameters->job_id(),
47
			$this->get_filename_from_event( $event_id )
48
		);
49
		$job_parameters->add_extra_data( 'filepath', $filepath );
50
		$question_data_for_columns = $this->_get_questions_for_report( $event_id );
51
		$job_parameters->add_extra_data( 'questions_data', $question_data_for_columns );
52
		$job_parameters->set_job_size( $this->count_units_to_process( $event_id ) );
53
		//we should also set the header columns
54
		$csv_data_for_row = $this->get_csv_data_for(
55
			$event_id,
56
			0,
57
			1,
58
			$job_parameters->extra_datum( 'questions_data' ) );
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('questions_data') targeting EventEspressoBatchReques...rameters::extra_datum() can also be of type string; however, EventEspressoBatchReques...ort::get_csv_data_for() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
59
		\EEH_Export::write_data_array_to_csv( $filepath, $csv_data_for_row, true );
60
		//if we actually processed a row there, record it
61
		if( $job_parameters->job_size() ) {
62
			$job_parameters->mark_processed( 1 );
63
		}
64
		return new JobStepResponse(
65
			$job_parameters,
66
			__( 'Registrations report started successfully...', 'event_espresso' )
67
		);
68
	}
69
70
71
72
	/**
73
	 * Creates teh filename form the event id (or lack thereof)
74
	 * @param int $event_id
75
	 * @return string
76
	 */
77
	protected function get_filename_from_event( $event_id ) {
78 View Code Duplication
		if( $event_id ){
79
			$event_slug =  \EEM_Event::instance()->get_var( array( array( 'EVT_ID' => $event_id ) ), 'EVT_slug' );
80
			if( ! $event_slug ) {
81
				$event_slug = __( 'unknown', 'event_espresso' );
82
			}
83
		}else{
84
			$event_slug = __( 'all', 'event_espresso' );
85
		}
86
		return sprintf( "registrations-for-%s.csv", $event_slug );
87
	}
88
89
	/**
90
	 * Gets the questions which are to be used for this report, so they
91
	 * can be remembered for later
92
	 * @param int|null $event_id
93
	 * @return array of wpdb results for questions which are to be used for this report
94
	 */
95
	protected function _get_questions_for_report( $event_id ) {
96
		$question_query_params = array(
97
			array(
98
				'Answer.ANS_ID' => array( 'IS_NOT_NULL' ),
99
			),
100
			'group_by' => array( 'QST_ID' )
101
		);
102
		if( $event_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $event_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
103
			$question_query_params[0]['Answer.Registration.EVT_ID'] = $event_id;
104
		}
105
		return \EEM_Question::instance()->get_all_wpdb_results( $question_query_params );
106
	}
107
108
109
110
	/**
111
	 * Performs another step of the job
112
	 *
113
	 * @param JobParameters $job_parameters
114
	 * @param int           $batch_size
115
	 * @return JobStepResponse
116
	 * @throws \EE_Error
117
	 */
118
	public function continue_job( JobParameters $job_parameters, $batch_size = 50 ) {
119
		$csv_data = $this->get_csv_data_for(
120
			$job_parameters->request_datum( 'EVT_ID', '0'),
0 ignored issues
show
Documentation introduced by
$job_parameters->request_datum('EVT_ID', '0') is of type string|array, but the function expects a integer|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
121
			$job_parameters->units_processed(),
122
			$batch_size,
123
			$job_parameters->extra_datum( 'questions_data' ) );
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('questions_data') targeting EventEspressoBatchReques...rameters::extra_datum() can also be of type string; however, EventEspressoBatchReques...ort::get_csv_data_for() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
124
		\EEH_Export::write_data_array_to_csv( $job_parameters->extra_datum( 'filepath' ), $csv_data, false );
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('filepath') targeting EventEspressoBatchReques...rameters::extra_datum() can also be of type array; however, EEH_Export::write_data_array_to_csv() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
125
		$units_processed = count( $csv_data );
126
		$job_parameters->mark_processed( $units_processed );
127
		$extra_response_data = array(
128
			'file_url' => ''
129
		);
130 View Code Duplication
		if( $units_processed < $batch_size ) {
131
			$job_parameters->set_status( JobParameters::status_complete );
132
			$extra_response_data[ 'file_url' ] = $this->get_url_to_file( $job_parameters->extra_datum( 'filepath' ) );
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('filepath') targeting EventEspressoBatchReques...rameters::extra_datum() can also be of type array; however, EventEspressoBatchReques...File::get_url_to_file() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
133
		}
134
		return new JobStepResponse(
135
				$job_parameters,
136
				sprintf(
137
					__( 'Wrote %1$s rows to report CSV file...', 'event_espresso' ),
138
					count( $csv_data ) ),
139
				$extra_response_data );
140
	}
141
142
	/**
143
	 * Gets the csv data for a batch of registrations
144
	 * @param int|null $event_id
145
	 * @param int $offset
146
	 * @param int $limit
147
	 * @param array $questions_for_these_regs_rows results of $wpdb->get_results( $something, ARRAY_A) when querying for questions
148
	 * @return array top-level keys are numeric, next-level keys are column headers
149
	 *
150
	 */
151
	function get_csv_data_for( $event_id, $offset, $limit, $questions_for_these_regs_rows ) {
152
		$reg_fields_to_include = array(
153
			'TXN_ID',
154
			'ATT_ID',
155
			'REG_ID',
156
			'REG_date',
157
			'REG_code',
158
			'REG_count',
159
			'REG_final_price',
160
		);
161
		$att_fields_to_include = array(
162
			'ATT_fname',
163
			'ATT_lname',
164
			'ATT_email',
165
			'ATT_address',
166
			'ATT_address2',
167
			'ATT_city',
168
			'STA_ID',
169
			'CNT_ISO',
170
			'ATT_zip',
171
			'ATT_phone',
172
		);
173
174
		$registrations_csv_ready_array = array();
175
		$reg_model = \EE_Registry::instance()->load_model('Registration');
176
		$query_params = apply_filters(
177
			'FHEE__EE_Export__report_registration_for_event',
178
			array(
179
				array(
180
					'OR' => array(
181
						//don't include registrations from failed or abandoned transactions...
182
						'Transaction.STS_ID' => array( 'NOT IN', array( \EEM_Transaction::failed_status_code, \EEM_Transaction::abandoned_status_code ) ),
183
						//unless the registration is approved, in which case include it regardless of transaction status
184
						'STS_ID' => \EEM_Registration::status_id_approved
185
						),
186
					'Ticket.TKT_deleted' => array( 'IN', array( true, false ) )
187
					),
188
				'order_by' => array('Transaction.TXN_ID'=>'asc','REG_count'=>'asc'),
189
				'force_join' => array( 'Transaction', 'Ticket', 'Attendee' ),
190
				'limit' => array( $offset, $limit ),
191
			),
192
			$event_id
193
		);
194 View Code Duplication
		if( $event_id ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $event_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
195
			$query_params[0]['EVT_ID'] =  $event_id;
196
		}else{
197
			$query_params[ 'force_join' ][] = 'Event';
198
		}
199
		$registration_rows = $reg_model->get_all_wpdb_results( $query_params );
200
		//get all questions which relate to someone in this group
201
		$registration_ids = array();
202
		foreach( $registration_rows as $reg_row ) {
203
			$registration_ids[] = intval( $reg_row[ 'Registration.REG_ID'] );
204
		}
205
206
		foreach($registration_rows as $reg_row){
207
			if ( is_array( $reg_row ) ) {
208
				$reg_csv_array = array();
209 View Code Duplication
				if( ! $event_id ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $event_id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
210
					//get the event's name and Id
211
					$reg_csv_array[ __( 'Event', 'event_espresso' ) ] = sprintf( __( '%1$s (%2$s)', 'event_espresso' ), \EEH_Export::prepare_value_from_db_for_display( \EEM_Event::instance(), 'EVT_name', $reg_row[ 'Event_CPT.post_title'] ), $reg_row[ 'Event_CPT.ID' ] );
212
				}
213
				$is_primary_reg = $reg_row[ 'Registration.REG_count' ] == '1' ? true : false;
214
				/*@var $reg_row EE_Registration */
215
				foreach($reg_fields_to_include as $field_name){
216
					$field = $reg_model->field_settings_for($field_name);
217
					if($field_name == 'REG_final_price'){
218
						$value = \EEH_Export::prepare_value_from_db_for_display( $reg_model, $field_name, $reg_row[ 'Registration.REG_final_price'], 'localized_float' );
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 175 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
219
					}elseif( $field_name == 'REG_count' ){
220
						$value = sprintf( __( '%s of %s', 'event_espresso' ), \EEH_Export::prepare_value_from_db_for_display( $reg_model, 'REG_count', $reg_row['Registration.REG_count'] ), \EEH_Export::prepare_value_from_db_for_display( $reg_model, 'REG_group_size', $reg_row['Registration.REG_group_size' ] ) );
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 175 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
221
					}elseif( $field_name == 'REG_date' ) {
222
						$value = \EEH_Export::prepare_value_from_db_for_display( $reg_model, $field_name, $reg_row[ 'Registration.REG_date'], 'no_html' );
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 175 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
223
					}else{
224
						$value = \EEH_Export::prepare_value_from_db_for_display( $reg_model, $field_name, $reg_row[ $field->get_qualified_column() ] );
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 175 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
225
					}
226
					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
227
					if($field_name == 'REG_final_price'){
228
						//add a column named Currency after the final price
229
						$reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
230
					}
231
				}
232
				//get pretty status
233
				$stati = \EEM_Status::instance()->localized_status( array(
234
					$reg_row[ 'Registration.STS_ID' ] => __( 'unknown', 'event_espresso' ),
235
					$reg_row[ 'Transaction.STS_ID' ] => __( 'unknown', 'event_espresso' ) ),
236
						FALSE,
237
						'sentence' );
238
				$reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[ $reg_row[ 'Registration.STS_ID' ] ];
239
				//get pretty transaction status
240
				$reg_csv_array[__("Transaction Status", 'event_espresso')] = $stati[ $reg_row[ 'Transaction.STS_ID' ] ];
241
				$reg_csv_array[ __( 'Transaction Amount Due', 'event_espresso' ) ] = $is_primary_reg ? \EEH_Export::prepare_value_from_db_for_display( \EEM_Transaction::instance(), 'TXN_total', $reg_row[ 'Transaction.TXN_total' ], 'localized_float' ) : '0.00';
242
				$reg_csv_array[ __( 'Amount Paid', 'event_espresso' )] = $is_primary_reg ? \EEH_Export::prepare_value_from_db_for_display( \EEM_Transaction::instance(), 'TXN_paid', $reg_row[ 'Transaction.TXN_paid' ], 'localized_float' ) : '0.00';
243
				$payment_methods = array();
244
				$gateway_txn_ids_etc = array();
245
				$payment_times = array();
246 View Code Duplication
				if( $is_primary_reg && $reg_row[ 'Transaction.TXN_ID' ] ){
247
					$payments_info = \EEM_Payment::instance()->get_all_wpdb_results(
248
							array(
249
								array(
250
									'TXN_ID' => $reg_row[ 'Transaction.TXN_ID' ],
251
									'STS_ID' => \EEM_Payment::status_id_approved
252
								),
253
								'force_join' => array( 'Payment_Method' ),
254
255
							),
256
							ARRAY_A,
257
							'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time' );
258
259
					foreach( $payments_info as $payment_method_and_gateway_txn_id ){
260
						$payment_methods[] = isset( $payment_method_and_gateway_txn_id[ 'name' ] ) ? $payment_method_and_gateway_txn_id[ 'name' ] : __( 'Unknown', 'event_espresso' );
261
						$gateway_txn_ids_etc[] = isset( $payment_method_and_gateway_txn_id[ 'gateway_txn_id' ] ) ? $payment_method_and_gateway_txn_id[ 'gateway_txn_id' ] : '';
262
						$payment_times[] = isset( $payment_method_and_gateway_txn_id[ 'payment_time' ] ) ? $payment_method_and_gateway_txn_id[ 'payment_time' ] : '';
263
					}
264
265
				}
266
				$reg_csv_array[ __( 'Payment Date(s)', 'event_espresso' ) ] = implode( ',', $payment_times );
267
				$reg_csv_array[ __( 'Payment Method(s)', 'event_espresso' ) ] = implode( ",", $payment_methods );
268
				$reg_csv_array[ __( 'Gateway Transaction ID(s)', 'event_espresso' )] = implode( ',', $gateway_txn_ids_etc );
269
270
				//get whether or not the user has checked in
271
				$reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related( $reg_row[ 'Registration.REG_ID'] , 'Checkin' );
272
				//get ticket of registration and its price
273
				$ticket_model = \EE_Registry::instance()->load_model('Ticket');
274
				if( $reg_row[ 'Ticket.TKT_ID'] ) {
275
					$ticket_name = \EEH_Export::prepare_value_from_db_for_display( $ticket_model, 'TKT_name', $reg_row[ 'Ticket.TKT_name' ] );
0 ignored issues
show
Bug introduced by
It seems like $ticket_model defined by \EE_Registry::instance()->load_model('Ticket') on line 273 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
276
					$datetimes_strings = array();
277 View Code Duplication
					foreach( \EEM_Datetime::instance()->get_all_wpdb_results( array( array( 'Ticket.TKT_ID' => $reg_row[ 'Ticket.TKT_ID' ] ), 'order_by' => array( 'DTT_EVT_start' => 'ASC' ), 'default_where_conditions' => 'none' ) ) as $datetime){
278
						$datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display( \EEM_Datetime::instance(), 'DTT_EVT_start', $datetime[ 'Datetime.DTT_EVT_start'] );
279
					}
280
281
				} else {
282
					$ticket_name = __( 'Unknown', 'event_espresso' );
283
					$datetimes_strings = array( __( 'Unknown', 'event_espresso' ) );
284
				}
285
				$reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
286
				$reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
287
				//get datetime(s) of registration
288
289
				//add attendee columns
290
				foreach($att_fields_to_include as $att_field_name){
291
					$field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
292 View Code Duplication
					if( $reg_row[ 'Attendee_CPT.ID' ]){
293
						if($att_field_name == 'STA_ID'){
294
							$value = \EEM_State::instance()->get_var( array( array( 'STA_ID' => $reg_row[ 'Attendee_Meta.STA_ID' ] ) ), 'STA_name' );
295
						}elseif($att_field_name == 'CNT_ISO'){
296
							$value = \EEM_Country::instance()->get_var( array( array( 'CNT_ISO' => $reg_row[ 'Attendee_Meta.CNT_ISO' ] ) ), 'CNT_name' );
297
						}else{
298
							$value = \EEH_Export::prepare_value_from_db_for_display( \EEM_Attendee::instance(), $att_field_name, $reg_row[ $field_obj->get_qualified_column() ] );
299
						}
300
					}else{
301
						$value = '';
302
					}
303
304
					$reg_csv_array[ \EEH_Export::get_column_name_for_field($field_obj) ] = $value;
305
				}
306
307
				//make sure each registration has the same questions in the same order
308 View Code Duplication
				foreach($questions_for_these_regs_rows as $question_row){
309
					if( ! isset($reg_csv_array[$question_row[ 'Question.QST_admin_label']])){
310
						$reg_csv_array[$question_row[ 'Question.QST_admin_label' ] ] = null;
311
					}
312
				}
313
				$answers = \EEM_Answer::instance()->get_all_wpdb_results(
314
					array(
315
						array( 'REG_ID' => $reg_row[ 'Registration.REG_ID' ] ),
316
						'force_join' => array( 'Question' )
317
					)
318
				);
319
				//now fill out the questions THEY answered
320
				foreach( $answers as $answer_row ){
321 View Code Duplication
					if( $answer_row[ 'Question.QST_ID' ] ){
322
						$question_label = \EEH_Export::prepare_value_from_db_for_display(
323
							\EEM_Question::instance(),
324
							'QST_admin_label',
325
							$answer_row[ 'Question.QST_admin_label' ]
326
						);
327
					} else {
328
						$question_label = sprintf( __( 'Question $s', 'event_espresso' ), $answer_row[ 'Answer.QST_ID' ] );
329
					}
330 View Code Duplication
					if ( isset( $answer_row[ 'Question.QST_type' ] )
331
						 && $answer_row[ 'Question.QST_type' ] == \EEM_Question::QST_type_state
332
					) {
333
						$reg_csv_array[ $question_label ] = \EEM_State::instance()->get_state_name_by_ID(
334
							$answer_row[ 'Answer.ANS_value' ]
335
						);
336
					} else {
337
						$reg_csv_array[ $question_label ] = \EEH_Export::prepare_value_from_db_for_display(
338
							\EEM_Answer::instance(),
339
							'ANS_value',
340
							$answer_row[ 'Answer.ANS_value' ]
341
						);
342
					}
343
				}
344
				$registrations_csv_ready_array[] = apply_filters(
345
					'FHEE__EE_Export__report_registrations__reg_csv_array',
346
					$reg_csv_array, $reg_row
347
				);
348
			}
349
		}
350
		//if we couldn't export anything, we want to at least show the column headers
351 View Code Duplication
		if ( empty( $registrations_csv_ready_array ) ) {
352
			$reg_csv_array = array();
353
			$model_and_fields_to_include = array(
354
				'Registration' => $reg_fields_to_include,
355
				'Attendee'     => $att_fields_to_include
356
			);
357
			foreach ( $model_and_fields_to_include as $model_name => $field_list ) {
358
				$model = \EE_Registry::instance()->load_model( $model_name );
359
				foreach ( $field_list as $field_name ) {
360
					$field = $model->field_settings_for( $field_name );
361
					$reg_csv_array[ \EEH_Export::get_column_name_for_field( $field ) ] = null;
362
				}
363
			}
364
			$registrations_csv_ready_array[] = $reg_csv_array;
365
		}
366
		return $registrations_csv_ready_array;
367
	}
368
369
370
371
	/**
372
	 * Counts total unit to process
373
	 *
374
	 * @param int $event_id
375
	 * @return int
376
	 */
377
	public function count_units_to_process( $event_id ) {
378
		//use the legacy filter
379
		$query_params = apply_filters(
380
			'FHEE__EE_Export__report_registration_for_event',
381
			array(
382
				array(
383
					'OR' => array(
384
						//don't include registrations from failed or abandoned transactions...
385
						'Transaction.STS_ID' => array( 'NOT IN', array( \EEM_Transaction::failed_status_code, \EEM_Transaction::abandoned_status_code ) ),
386
						//unless the registration is approved, in which case include it regardless of transaction status
387
						'STS_ID' => \EEM_Registration::status_id_approved
388
						),
389
					'Ticket.TKT_deleted' => array( 'IN', array( true, false ) )
390
					),
391
				'order_by' => array('Transaction.TXN_ID'=>'asc','REG_count'=>'asc'),
392
				'force_join' => array( 'Transaction', 'Ticket', 'Attendee' )
393
			),
394
			$event_id
395
		);
396 View Code Duplication
		if( $event_id ){
397
			$query_params[0]['EVT_ID'] =  $event_id;
398
		} else {
399
			$query_params[ 'force_join' ][] = 'Event';
400
		}
401
		return \EEM_Registration::instance()->count( $query_params );
402
	}
403
404
405
406
	/**
407
	 * Performs any clean-up logic when we know the job is completed.
408
	 * In this case, we delete the temporary file
409
	 * @param JobParameters $job_parameters
410
	 * @return boolean
411
	 */
412 View Code Duplication
	public function cleanup_job( JobParameters $job_parameters ){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
413
		$this->_file_helper->delete(
414
			\EEH_File::remove_filename_from_filepath( $job_parameters->extra_datum( 'filepath' ) ),
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('filepath') targeting EventEspressoBatchReques...rameters::extra_datum() can also be of type array; however, EEH_File::remove_filename_from_filepath() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
415
			true,
416
			'd'
417
		);
418
		return new JobStepResponse( $job_parameters, __( 'Cleaned up temporary file', 'event_espresso' ) );
419
	}
420
}
421
422
423