Completed
Branch Gutenberg/event-attendees-bloc... (e27df5)
by
unknown
42:51 queued 28:10
created

RegistrationsReport   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 522
Duplicated Lines 19.16 %

Coupling/Cohesion

Components 2
Dependencies 22

Importance

Changes 0
Metric Value
dl 100
loc 522
rs 6.4799
c 0
b 0
f 0
wmc 54
lcom 2
cbo 22

8 Methods

Rating   Name   Duplication   Size   Complexity  
B create_job() 5 74 6
A get_filename() 0 4 1
A _get_question_labels() 0 23 4
A _change_registration_where_params_to_question_where_params() 0 13 3
A continue_job() 4 30 3
F get_csv_data_for() 78 281 34
A count_units_to_process() 5 10 2
A cleanup_job() 8 9 1

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
namespace EventEspressoBatchRequest\JobHandlers;
4
5
use EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile;
6
use EventEspressoBatchRequest\Helpers\BatchRequestException;
7
use EventEspressoBatchRequest\Helpers\JobParameters;
8
use EventEspressoBatchRequest\Helpers\JobStepResponse;
9
10
/**
11
 * Class RegistrationsReport
12
 * Generates the registrations report for the specified event,
13
 * or for all events
14
 *
15
 * @package               Event Espresso
16
 * @subpackage            batch
17
 * @author                Mike Nelson
18
 * @since                 4.8.26
19
 */
20
class RegistrationsReport extends JobHandlerFile
21
{
22
    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
23
    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
24
    /**
25
     * Performs any necessary setup for starting the job. This is also a good
26
     * place to setup the $job_arguments which will be used for subsequent HTTP requests
27
     * when continue_job will be called
28
     *
29
     * @param JobParameters $job_parameters
30
     * @throws BatchRequestException
31
     * @return JobStepResponse
32
     */
33
    public function create_job(JobParameters $job_parameters)
34
    {
35
        $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
36
        if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
37
            throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
38
        }
39
        $filepath = $this->create_file_from_job_with_name(
40
            $job_parameters->job_id(),
41
            $this->get_filename($event_id)
42
        );
43
        $job_parameters->add_extra_data('filepath', $filepath);
44
        if ($job_parameters->request_datum('use_filters', false)) {
45
            $query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
46
        } else {
47
            $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
48
                array(
49
                    'OR'                 => array(
50
                        // don't include registrations from failed or abandoned transactions...
51
                        'Transaction.STS_ID' => array(
52
                            'NOT IN',
53
                            array(
54
                                \EEM_Transaction::failed_status_code,
55
                                \EEM_Transaction::abandoned_status_code,
56
                            ),
57
                        ),
58
                        // unless the registration is approved, in which case include it regardless of transaction status
59
                        'STS_ID'             => \EEM_Registration::status_id_approved,
60
                    ),
61
                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
62
                ),
63
                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
64
                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
65
                'caps'       => \EEM_Base::caps_read_admin,
66
            ), $event_id);
67 View Code Duplication
            if ($event_id) {
68
                $query_params[0]['EVT_ID'] = $event_id;
69
            } else {
70
                $query_params['force_join'][] = 'Event';
71
            }
72
        }
73
        if (! isset($query_params['force_join'])) {
74
            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
75
        }
76
        $job_parameters->add_extra_data('query_params', $query_params);
77
        $question_labels = $this->_get_question_labels($query_params);
78
        $job_parameters->add_extra_data('question_labels', $question_labels);
79
        $job_parameters->set_job_size(
80
            \EEM_Registration::instance()->count(
81
                array_diff_key(
82
                    $query_params,
83
                    array_flip(
84
                        array('limit')
85
                    )
86
                )
87
            )
88
        );
89
        // we should also set the header columns
90
        $csv_data_for_row = $this->get_csv_data_for(
91
            $event_id,
92
            0,
93
            1,
94
            $job_parameters->extra_datum('question_labels'),
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('question_labels') 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...
95
            $job_parameters->extra_datum('query_params')
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('query_params') 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...
96
        );
97
        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
98
        // if we actually processed a row there, record it
99
        if ($job_parameters->job_size()) {
100
            $job_parameters->mark_processed(1);
101
        }
102
        return new JobStepResponse(
103
            $job_parameters,
104
            __('Registrations report started successfully...', 'event_espresso')
105
        );
106
    }
107
108
109
    /**
110
     * Gets the filename
111
     *
112
     * @return string
113
     */
114
    protected function get_filename()
115
    {
116
        return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
117
    }
118
119
120
    /**
121
     * Gets the questions which are to be used for this report, so they
122
     * can be remembered for later
123
     *
124
     * @param array $registration_query_params
125
     * @return array question admin labels to be used for this report
126
     */
127
    protected function _get_question_labels($registration_query_params)
128
    {
129
        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
130
        $question_query_params = array();
131
        if ($where !== null) {
132
            $question_query_params = array(
133
                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
134
            );
135
        }
136
        $question_query_params[0]['QST_system'] = array(
137
            'NOT_IN',
138
            array_keys(\EEM_Attendee::instance()->system_question_to_attendee_field_mapping()),
139
        );
140
        if (apply_filters(
141
            'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
142
            false,
143
            $registration_query_params
144
        )) {
145
            $question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
146
        }
147
        $question_query_params['group_by'] = array('QST_ID');
148
        return array_unique(\EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
149
    }
150
151
152
    /**
153
     * Takes where params meant for registrations and changes them to work for questions
154
     *
155
     * @param array $reg_where_params
156
     * @return array
157
     */
158
    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
159
    {
160
        $question_where_params = array();
161
        foreach ($reg_where_params as $key => $val) {
162
            if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
163
                $question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
164
            } else {
165
                // it's a normal where condition
166
                $question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
167
            }
168
        }
169
        return $question_where_params;
170
    }
171
172
173
    /**
174
     * Performs another step of the job
175
     *
176
     * @param JobParameters $job_parameters
177
     * @param int           $batch_size
178
     * @return JobStepResponse
179
     * @throws \EE_Error
180
     */
181
    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
182
    {
183
        if ($job_parameters->units_processed() < $job_parameters->job_size()) {
184
            $csv_data = $this->get_csv_data_for(
185
                $job_parameters->request_datum('EVT_ID', '0'),
186
                $job_parameters->units_processed(),
187
                $batch_size,
188
                $job_parameters->extra_datum('question_labels'),
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('question_labels') 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...
189
                $job_parameters->extra_datum('query_params')
0 ignored issues
show
Bug introduced by
It seems like $job_parameters->extra_datum('query_params') 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...
190
            );
191
            \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...
192
            $units_processed = count($csv_data);
193
        } else {
194
            $units_processed = 0;
195
        }
196
        $job_parameters->mark_processed($units_processed);
197
        $extra_response_data = array(
198
            'file_url' => '',
199
        );
200 View Code Duplication
        if ($units_processed < $batch_size) {
201
            $job_parameters->set_status(JobParameters::status_complete);
202
            $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...
203
        }
204
205
        return new JobStepResponse(
206
            $job_parameters,
207
            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
208
            $extra_response_data
209
        );
210
    }
211
212
213
    /**
214
     * Gets the csv data for a batch of registrations
215
     *
216
     * @param int|null $event_id
217
     * @param int      $offset
218
     * @param int      $limit
219
     * @param array    $question_labels the IDs for all the questions which were answered by someone in this selection
220
     * @param array    $query_params    for using where querying the model
221
     * @return array top-level keys are numeric, next-level keys are column headers
222
     */
223
    public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
224
    {
225
        $reg_fields_to_include = array(
226
            'TXN_ID',
227
            'ATT_ID',
228
            'REG_ID',
229
            'REG_date',
230
            'REG_code',
231
            'REG_count',
232
            'REG_final_price',
233
        );
234
        $att_fields_to_include = array(
235
            'ATT_fname',
236
            'ATT_lname',
237
            'ATT_email',
238
            'ATT_address',
239
            'ATT_address2',
240
            'ATT_city',
241
            'STA_ID',
242
            'CNT_ISO',
243
            'ATT_zip',
244
            'ATT_phone',
245
        );
246
        $registrations_csv_ready_array = array();
247
        $reg_model = \EE_Registry::instance()->load_model('Registration');
248
        $query_params['limit'] = array($offset, $limit);
249
        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
250
        $registration_ids = array();
251
        foreach ($registration_rows as $reg_row) {
252
            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
253
        }
254
        foreach ($registration_rows as $reg_row) {
255
            if (is_array($reg_row)) {
256
                $reg_csv_array = array();
257 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...
258
                    // get the event's name and Id
259
                    $reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
260
                        __('%1$s (%2$s)', 'event_espresso'),
261
                        \EEH_Export::prepare_value_from_db_for_display(
262
                            \EEM_Event::instance(),
263
                            'EVT_name',
264
                            $reg_row['Event_CPT.post_title']
265
                        ),
266
                        $reg_row['Event_CPT.ID']
267
                    );
268
                }
269
                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
270
                /*@var $reg_row EE_Registration */
271
                foreach ($reg_fields_to_include as $field_name) {
272
                    $field = $reg_model->field_settings_for($field_name);
273
                    if ($field_name == 'REG_final_price') {
274
                        $value = \EEH_Export::prepare_value_from_db_for_display(
275
                            $reg_model,
276
                            $field_name,
277
                            $reg_row['Registration.REG_final_price'],
278
                            'localized_float'
279
                        );
280
                    } elseif ($field_name == 'REG_count') {
281
                        $value = sprintf(
282
                            __('%1$s of %2$s', 'event_espresso'),
283
                            \EEH_Export::prepare_value_from_db_for_display(
284
                                $reg_model,
285
                                'REG_count',
286
                                $reg_row['Registration.REG_count']
287
                            ),
288
                            \EEH_Export::prepare_value_from_db_for_display(
289
                                $reg_model,
290
                                'REG_group_size',
291
                                $reg_row['Registration.REG_group_size']
292
                            )
293
                        );
294
                    } elseif ($field_name == 'REG_date') {
295
                        $value = \EEH_Export::prepare_value_from_db_for_display(
296
                            $reg_model,
297
                            $field_name,
298
                            $reg_row['Registration.REG_date'],
299
                            'no_html'
300
                        );
301
                    } else {
302
                        $value = \EEH_Export::prepare_value_from_db_for_display(
303
                            $reg_model,
304
                            $field_name,
305
                            $reg_row[ $field->get_qualified_column() ]
306
                        );
307
                    }
308
                    $reg_csv_array[ \EEH_Export::get_column_name_for_field($field) ] = $value;
309
                    if ($field_name == 'REG_final_price') {
310
                        // add a column named Currency after the final price
311
                        $reg_csv_array[ __("Currency", "event_espresso") ] = \EE_Config::instance()->currency->code;
312
                    }
313
                }
314
                // get pretty status
315
                $stati = \EEM_Status::instance()->localized_status(
316
                    array(
317
                        $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
318
                        $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
319
                    ),
320
                    false,
321
                    'sentence'
322
                );
323
                $reg_csv_array[ __("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
324
                // get pretty transaction status
325
                $reg_csv_array[ __("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
326
                $reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
327
                    ? \EEH_Export::prepare_value_from_db_for_display(
328
                        \EEM_Transaction::instance(),
329
                        'TXN_total',
330
                        $reg_row['TransactionTable.TXN_total'],
331
                        'localized_float'
332
                    ) : '0.00';
333
                $reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
334
                    ? \EEH_Export::prepare_value_from_db_for_display(
335
                        \EEM_Transaction::instance(),
336
                        'TXN_paid',
337
                        $reg_row['TransactionTable.TXN_paid'],
338
                        'localized_float'
339
                    ) : '0.00';
340
                $payment_methods = array();
341
                $gateway_txn_ids_etc = array();
342
                $payment_times = array();
343 View Code Duplication
                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
344
                    $payments_info = \EEM_Payment::instance()->get_all_wpdb_results(
345
                        array(
346
                            array(
347
                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
348
                                'STS_ID' => \EEM_Payment::status_id_approved,
349
                            ),
350
                            'force_join' => array('Payment_Method'),
351
                        ),
352
                        ARRAY_A,
353
                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
354
                    );
355
                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
356
                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
357
                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
358
                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
359
                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
360
                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
361
                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
362
                    }
363
                }
364
                $reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
365
                $reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
366
                $reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
367
                    ',',
368
                    $gateway_txn_ids_etc
369
                );
370
                // get whether or not the user has checked in
371
                $reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
372
                    $reg_row['Registration.REG_ID'],
373
                    'Checkin'
374
                );
375
                // get ticket of registration and its price
376
                $ticket_model = \EE_Registry::instance()->load_model('Ticket');
377
                if ($reg_row['Ticket.TKT_ID']) {
378
                    $ticket_name = \EEH_Export::prepare_value_from_db_for_display(
379
                        $ticket_model,
380
                        'TKT_name',
381
                        $reg_row['Ticket.TKT_name']
382
                    );
383
                    $datetimes_strings = array();
384 View Code Duplication
                    foreach (\EEM_Datetime::instance()->get_all_wpdb_results(
385
                        array(
386
                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
387
                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
388
                            'default_where_conditions' => 'none',
389
                        )
390
                    ) as $datetime) {
391
                        $datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(
392
                            \EEM_Datetime::instance(),
393
                            'DTT_EVT_start',
394
                            $datetime['Datetime.DTT_EVT_start']
395
                        );
396
                    }
397
                } else {
398
                    $ticket_name = __('Unknown', 'event_espresso');
399
                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
400
                }
401
                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
402
                $reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
403
                // get datetime(s) of registration
404
                // add attendee columns
405
                foreach ($att_fields_to_include as $att_field_name) {
406
                    $field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
407 View Code Duplication
                    if ($reg_row['Attendee_CPT.ID']) {
408
                        if ($att_field_name == 'STA_ID') {
409
                            $value = \EEM_State::instance()->get_var(
410
                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
411
                                'STA_name'
412
                            );
413
                        } elseif ($att_field_name == 'CNT_ISO') {
414
                            $value = \EEM_Country::instance()->get_var(
415
                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
416
                                'CNT_name'
417
                            );
418
                        } else {
419
                            $value = \EEH_Export::prepare_value_from_db_for_display(
420
                                \EEM_Attendee::instance(),
421
                                $att_field_name,
422
                                $reg_row[ $field_obj->get_qualified_column() ]
423
                            );
424
                        }
425
                    } else {
426
                        $value = '';
427
                    }
428
                    $reg_csv_array[ \EEH_Export::get_column_name_for_field($field_obj) ] = $value;
429
                }
430
                // make sure each registration has the same questions in the same order
431
                foreach ($question_labels as $question_label) {
432
                    if (! isset($reg_csv_array[ $question_label ])) {
433
                        $reg_csv_array[ $question_label ] = null;
434
                    }
435
                }
436
                $answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
437
                    array('REG_ID' => $reg_row['Registration.REG_ID']),
438
                    'force_join' => array('Question'),
439
                ));
440
                // now fill out the questions THEY answered
441
                foreach ($answers as $answer_row) {
442 View Code Duplication
                    if ($answer_row['Question.QST_ID']) {
443
                        $question_label = \EEH_Export::prepare_value_from_db_for_display(
444
                            \EEM_Question::instance(),
445
                            'QST_admin_label',
446
                            $answer_row['Question.QST_admin_label']
447
                        );
448
                    } else {
449
                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
450
                    }
451 View Code Duplication
                    if (isset($answer_row['Question.QST_type'])
452
                        && $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
453
                    ) {
454
                        $reg_csv_array[ $question_label ] = \EEM_State::instance()->get_state_name_by_ID(
455
                            $answer_row['Answer.ANS_value']
456
                        );
457
                    } else {
458
                        // this isn't for html, so don't show html entities
459
                        $reg_csv_array[ $question_label ] = html_entity_decode(
460
                            \EEH_Export::prepare_value_from_db_for_display(
461
                                \EEM_Answer::instance(),
462
                                'ANS_value',
463
                                $answer_row['Answer.ANS_value']
464
                            )
465
                        );
466
                    }
467
                }
468
                /**
469
                 * Filter to change the contents of each row of the registrations report CSV file.
470
                 * This can be used to add or remote columns from the CSV file, or change their values.                 *
471
                 * Note: it has this name because originally that's where this filter resided,
472
                 * and we've left its name as-is for backward compatibility.
473
                 * Note when using: all rows in the CSV should have the same columns.
474
                 *
475
                 * @param array $reg_csv_array keys are column-header names, and values are that columns' value
476
                 *                             in this row
477
                 * @param array $reg_row       is the row from the database's wp_esp_registration table
478
                 */
479
                $registrations_csv_ready_array[] = apply_filters(
480
                    'FHEE__EE_Export__report_registrations__reg_csv_array',
481
                    $reg_csv_array,
482
                    $reg_row
483
                );
484
            }
485
        }
486
        // if we couldn't export anything, we want to at least show the column headers
487 View Code Duplication
        if (empty($registrations_csv_ready_array)) {
488
            $reg_csv_array = array();
489
            $model_and_fields_to_include = array(
490
                'Registration' => $reg_fields_to_include,
491
                'Attendee'     => $att_fields_to_include,
492
            );
493
            foreach ($model_and_fields_to_include as $model_name => $field_list) {
494
                $model = \EE_Registry::instance()->load_model($model_name);
495
                foreach ($field_list as $field_name) {
496
                    $field = $model->field_settings_for($field_name);
497
                    $reg_csv_array[ \EEH_Export::get_column_name_for_field($field) ] = null;
498
                }
499
            }
500
            $registrations_csv_ready_array[] = $reg_csv_array;
501
        }
502
        return $registrations_csv_ready_array;
503
    }
504
505
506
    /**
507
     * Counts total unit to process
508
     *
509
     * @deprecated since 4.9.19
510
     * @param int|array $event_id
511
     * @return int
512
     */
513
    public function count_units_to_process($event_id)
514
    {
515
        // use the legacy filter
516 View Code Duplication
        if ($event_id) {
517
            $query_params[0]['EVT_ID'] = $event_id;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$query_params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
518
        } else {
519
            $query_params['force_join'][] = 'Event';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$query_params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
520
        }
521
        return \EEM_Registration::instance()->count($query_params);
522
    }
523
524
525
    /**
526
     * Performs any clean-up logic when we know the job is completed.
527
     * In this case, we delete the temporary file
528
     *
529
     * @param JobParameters $job_parameters
530
     * @return boolean
531
     */
532 View Code Duplication
    public function cleanup_job(JobParameters $job_parameters)
533
    {
534
        $this->_file_helper->delete(
535
            \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...
536
            true,
537
            'd'
538
        );
539
        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
540
    }
541
}
542