Completed
Branch BUG-9623-config-log (c144cd)
by
unknown
110:09 queued 92:18
created

RegistrationsReport   F

Complexity

Total Complexity 48

Size/Duplication

Total Lines 395
Duplicated Lines 27.85 %

Coupling/Cohesion

Components 2
Dependencies 22

Importance

Changes 0
Metric Value
dl 110
loc 395
rs 3.894
c 0
b 0
f 0
wmc 48
lcom 2
cbo 22

7 Methods

Rating   Name   Duplication   Size   Complexity  
B create_job() 0 31 3
A get_filename_from_event() 8 11 3
A _get_questions_for_report() 0 12 2
A continue_job() 4 23 2
B count_units_to_process() 5 27 2
A cleanup_job() 8 8 1
F get_csv_data_for() 85 218 35

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RegistrationsReport often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RegistrationsReport, and based on these observations, apply Extract Interface, too.

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
				'caps' => \EEM_Base::caps_read_admin
192
			),
193
			$event_id
194
		);
195 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...
196
			$query_params[0]['EVT_ID'] =  $event_id;
197
		}else{
198
			$query_params[ 'force_join' ][] = 'Event';
199
		}
200
		$registration_rows = $reg_model->get_all_wpdb_results( $query_params );
201
		//get all questions which relate to someone in this group
202
		$registration_ids = array();
203
		foreach( $registration_rows as $reg_row ) {
204
			$registration_ids[] = intval( $reg_row[ 'Registration.REG_ID'] );
205
		}
206
207
		foreach($registration_rows as $reg_row){
208
			if ( is_array( $reg_row ) ) {
209
				$reg_csv_array = array();
210 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...
211
					//get the event's name and Id
212
					$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' ] );
213
				}
214
				$is_primary_reg = $reg_row[ 'Registration.REG_count' ] == '1' ? true : false;
215
				/*@var $reg_row EE_Registration */
216
				foreach($reg_fields_to_include as $field_name){
217
					$field = $reg_model->field_settings_for($field_name);
218
					if($field_name == 'REG_final_price'){
219
						$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...
220
					}elseif( $field_name == 'REG_count' ){
221
						$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...
222
					}elseif( $field_name == 'REG_date' ) {
223
						$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...
224
					}else{
225
						$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...
226
					}
227
					$reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
228
					if($field_name == 'REG_final_price'){
229
						//add a column named Currency after the final price
230
						$reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
231
					}
232
				}
233
				//get pretty status
234
				$stati = \EEM_Status::instance()->localized_status( array(
235
					$reg_row[ 'Registration.STS_ID' ] => __( 'unknown', 'event_espresso' ),
236
					$reg_row[ 'TransactionTable.STS_ID' ] => __( 'unknown', 'event_espresso' ) ),
237
						FALSE,
238
						'sentence' );
239
				$reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[ $reg_row[ 'Registration.STS_ID' ] ];
240
				//get pretty transaction status
241
				$reg_csv_array[__("Transaction Status", 'event_espresso')] = $stati[ $reg_row[ 'TransactionTable.STS_ID' ] ];
242
				$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[ 'TransactionTable.TXN_total' ], 'localized_float' ) : '0.00';
243
				$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[ 'TransactionTable.TXN_paid' ], 'localized_float' ) : '0.00';
244
				$payment_methods = array();
245
				$gateway_txn_ids_etc = array();
246
				$payment_times = array();
247 View Code Duplication
				if( $is_primary_reg && $reg_row[ 'TransactionTable.TXN_ID' ] ){
248
					$payments_info = \EEM_Payment::instance()->get_all_wpdb_results(
249
							array(
250
								array(
251
									'TXN_ID' => $reg_row[ 'TransactionTable.TXN_ID' ],
252
									'STS_ID' => \EEM_Payment::status_id_approved
253
								),
254
								'force_join' => array( 'Payment_Method' ),
255
256
							),
257
							ARRAY_A,
258
							'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time' );
259
260
					foreach( $payments_info as $payment_method_and_gateway_txn_id ){
261
						$payment_methods[] = isset( $payment_method_and_gateway_txn_id[ 'name' ] ) ? $payment_method_and_gateway_txn_id[ 'name' ] : __( 'Unknown', 'event_espresso' );
262
						$gateway_txn_ids_etc[] = isset( $payment_method_and_gateway_txn_id[ 'gateway_txn_id' ] ) ? $payment_method_and_gateway_txn_id[ 'gateway_txn_id' ] : '';
263
						$payment_times[] = isset( $payment_method_and_gateway_txn_id[ 'payment_time' ] ) ? $payment_method_and_gateway_txn_id[ 'payment_time' ] : '';
264
					}
265
266
				}
267
				$reg_csv_array[ __( 'Payment Date(s)', 'event_espresso' ) ] = implode( ',', $payment_times );
268
				$reg_csv_array[ __( 'Payment Method(s)', 'event_espresso' ) ] = implode( ",", $payment_methods );
269
				$reg_csv_array[ __( 'Gateway Transaction ID(s)', 'event_espresso' )] = implode( ',', $gateway_txn_ids_etc );
270
271
				//get whether or not the user has checked in
272
				$reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related( $reg_row[ 'Registration.REG_ID'] , 'Checkin' );
273
				//get ticket of registration and its price
274
				$ticket_model = \EE_Registry::instance()->load_model('Ticket');
275
				if( $reg_row[ 'Ticket.TKT_ID'] ) {
276
					$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 274 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...
277
					$datetimes_strings = array();
278 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){
279
						$datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display( \EEM_Datetime::instance(), 'DTT_EVT_start', $datetime[ 'Datetime.DTT_EVT_start'] );
280
					}
281
282
				} else {
283
					$ticket_name = __( 'Unknown', 'event_espresso' );
284
					$datetimes_strings = array( __( 'Unknown', 'event_espresso' ) );
285
				}
286
				$reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
287
				$reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
288
				//get datetime(s) of registration
289
290
				//add attendee columns
291
				foreach($att_fields_to_include as $att_field_name){
292
					$field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
293 View Code Duplication
					if( $reg_row[ 'Attendee_CPT.ID' ]){
294
						if($att_field_name == 'STA_ID'){
295
							$value = \EEM_State::instance()->get_var( array( array( 'STA_ID' => $reg_row[ 'Attendee_Meta.STA_ID' ] ) ), 'STA_name' );
296
						}elseif($att_field_name == 'CNT_ISO'){
297
							$value = \EEM_Country::instance()->get_var( array( array( 'CNT_ISO' => $reg_row[ 'Attendee_Meta.CNT_ISO' ] ) ), 'CNT_name' );
298
						}else{
299
							$value = \EEH_Export::prepare_value_from_db_for_display( \EEM_Attendee::instance(), $att_field_name, $reg_row[ $field_obj->get_qualified_column() ] );
300
						}
301
					}else{
302
						$value = '';
303
					}
304
305
					$reg_csv_array[ \EEH_Export::get_column_name_for_field($field_obj) ] = $value;
306
				}
307
308
				//make sure each registration has the same questions in the same order
309 View Code Duplication
				foreach($questions_for_these_regs_rows as $question_row){
310
					if( ! isset($reg_csv_array[$question_row[ 'Question.QST_admin_label']])){
311
						$reg_csv_array[$question_row[ 'Question.QST_admin_label' ] ] = null;
312
					}
313
				}
314
				$answers = \EEM_Answer::instance()->get_all_wpdb_results(
315
					array(
316
						array( 'REG_ID' => $reg_row[ 'Registration.REG_ID' ] ),
317
						'force_join' => array( 'Question' )
318
					)
319
				);
320
				//now fill out the questions THEY answered
321
				foreach( $answers as $answer_row ){
322 View Code Duplication
					if( $answer_row[ 'Question.QST_ID' ] ){
323
						$question_label = \EEH_Export::prepare_value_from_db_for_display(
324
							\EEM_Question::instance(),
325
							'QST_admin_label',
326
							$answer_row[ 'Question.QST_admin_label' ]
327
						);
328
					} else {
329
						$question_label = sprintf( __( 'Question $s', 'event_espresso' ), $answer_row[ 'Answer.QST_ID' ] );
330
					}
331 View Code Duplication
					if ( isset( $answer_row[ 'Question.QST_type' ] )
332
						 && $answer_row[ 'Question.QST_type' ] == \EEM_Question::QST_type_state
333
					) {
334
						$reg_csv_array[ $question_label ] = \EEM_State::instance()->get_state_name_by_ID(
335
							$answer_row[ 'Answer.ANS_value' ]
336
						);
337
					} else {
338
						$reg_csv_array[ $question_label ] = \EEH_Export::prepare_value_from_db_for_display(
339
							\EEM_Answer::instance(),
340
							'ANS_value',
341
							$answer_row[ 'Answer.ANS_value' ]
342
						);
343
					}
344
				}
345
				$registrations_csv_ready_array[] = apply_filters(
346
					'FHEE__EE_Export__report_registrations__reg_csv_array',
347
					$reg_csv_array, $reg_row
348
				);
349
			}
350
		}
351
		//if we couldn't export anything, we want to at least show the column headers
352 View Code Duplication
		if ( empty( $registrations_csv_ready_array ) ) {
353
			$reg_csv_array = array();
354
			$model_and_fields_to_include = array(
355
				'Registration' => $reg_fields_to_include,
356
				'Attendee'     => $att_fields_to_include
357
			);
358
			foreach ( $model_and_fields_to_include as $model_name => $field_list ) {
359
				$model = \EE_Registry::instance()->load_model( $model_name );
360
				foreach ( $field_list as $field_name ) {
361
					$field = $model->field_settings_for( $field_name );
362
					$reg_csv_array[ \EEH_Export::get_column_name_for_field( $field ) ] = null;
363
				}
364
			}
365
			$registrations_csv_ready_array[] = $reg_csv_array;
366
		}
367
		return $registrations_csv_ready_array;
368
	}
369
370
371
372
	/**
373
	 * Counts total unit to process
374
	 *
375
	 * @param int $event_id
376
	 * @return int
377
	 */
378
	public function count_units_to_process( $event_id ) {
379
		//use the legacy filter
380
		$query_params = apply_filters(
381
			'FHEE__EE_Export__report_registration_for_event',
382
			array(
383
				array(
384
					'OR' => array(
385
						//don't include registrations from failed or abandoned transactions...
386
						'Transaction.STS_ID' => array( 'NOT IN', array( \EEM_Transaction::failed_status_code, \EEM_Transaction::abandoned_status_code ) ),
387
						//unless the registration is approved, in which case include it regardless of transaction status
388
						'STS_ID' => \EEM_Registration::status_id_approved
389
						),
390
					'Ticket.TKT_deleted' => array( 'IN', array( true, false ) )
391
					),
392
				'order_by' => array('Transaction.TXN_ID'=>'asc','REG_count'=>'asc'),
393
				'force_join' => array( 'Transaction', 'Ticket', 'Attendee' ),
394
				'caps' => \EEM_Base::caps_read_admin
395
			),
396
			$event_id
397
		);
398 View Code Duplication
		if( $event_id ){
399
			$query_params[0]['EVT_ID'] =  $event_id;
400
		} else {
401
			$query_params[ 'force_join' ][] = 'Event';
402
		}
403
		return \EEM_Registration::instance()->count( $query_params );
404
	}
405
406
407
408
	/**
409
	 * Performs any clean-up logic when we know the job is completed.
410
	 * In this case, we delete the temporary file
411
	 * @param JobParameters $job_parameters
412
	 * @return boolean
413
	 */
414 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...
415
		$this->_file_helper->delete(
416
			\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...
417
			true,
418
			'd'
419
		);
420
		return new JobStepResponse( $job_parameters, __( 'Cleaned up temporary file', 'event_espresso' ) );
421
	}
422
}
423
424
425