Completed
Branch FET-8385-datetime-ticket-selec... (ec342c)
by
unknown
45:18 queued 34:32
created

RegistrationsReport::create_job()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 65
Code Lines 46

Duplication

Lines 5
Ratio 7.69 %

Importance

Changes 0
Metric Value
cc 6
eloc 46
nc 13
nop 1
dl 5
loc 65
rs 8.6195
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Class RegistrationsReport
4
 * Generates the registrations report for the specified event,
5
 * or for all events
6
 *
7
 * @package               Event Espresso
8
 * @subpackage            batch
9
 * @author                Mike Nelson
10
 * @since                 4.8.26
11
 */
12
namespace EventEspressoBatchRequest\JobHandlers;
13
14
use EventEspressoBatchRequest\JobHandlerBaseClasses\JobHandlerFile;
15
use EventEspressoBatchRequest\Helpers\BatchRequestException;
16
use EventEspressoBatchRequest\Helpers\JobParameters;
17
use EventEspressoBatchRequest\Helpers\JobStepResponse;
18
19
if ( ! defined('EVENT_ESPRESSO_VERSION')) {
20
    exit('No direct script access allowed');
21
}
22
23
24
25
class RegistrationsReport extends JobHandlerFile
26
{
27
28
    /**
29
     * Performs any necessary setup for starting the job. This is also a good
30
     * place to setup the $job_arguments which will be used for subsequent HTTP requests
31
     * when continue_job will be called
32
     *
33
     * @param JobParameters $job_parameters
34
     * @throws BatchRequestException
35
     * @return JobStepResponse
36
     */
37
    public function create_job(JobParameters $job_parameters)
38
    {
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(__('You do not have permission to view registrations', 'event_espresso'));
42
        }
43
        $filepath = $this->create_file_from_job_with_name($job_parameters->job_id(),
44
            $this->get_filename($event_id));
0 ignored issues
show
Unused Code introduced by
The call to RegistrationsReport::get_filename() has too many arguments starting with $event_id.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
45
        $job_parameters->add_extra_data('filepath', $filepath);
46
        if ($job_parameters->request_datum('use_filters', false)) {
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|array.

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...
47
            $query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
48
        } else {
49
            $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
50
                array(
51
                    'OR'                 => array(
52
                        //don't include registrations from failed or abandoned transactions...
53
                        'Transaction.STS_ID' => array(
54
                            'NOT IN',
55
                            array(
56
                                \EEM_Transaction::failed_status_code,
57
                                \EEM_Transaction::abandoned_status_code,
58
                            ),
59
                        ),
60
                        //unless the registration is approved, in which case include it regardless of transaction status
61
                        'STS_ID'             => \EEM_Registration::status_id_approved,
62
                    ),
63
                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
64
                ),
65
                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
66
                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
67
                'caps'       => \EEM_Base::caps_read_admin,
68
            ), $event_id);
69 View Code Duplication
            if ($event_id) {
70
                $query_params[0]['EVT_ID'] = $event_id;
71
            } else {
72
                $query_params['force_join'][] = 'Event';
73
            }
74
        }
75
        if ( ! isset($query_params['force_join'])) {
76
            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
77
        }
78
        $job_parameters->add_extra_data('query_params', $query_params);
79
        $question_labels = $this->_get_question_labels($query_params);
80
        $job_parameters->add_extra_data('question_labels', $question_labels);
81
        $job_parameters->set_job_size(
82
            \EEM_Registration::instance()->count(
83
                array_diff_key(
84
                    $query_params,
85
                    array_flip(
86
                        array( 'limit' )
87
                    )
88
                )
89
            )
90
        );
91
        //we should also set the header columns
92
        $csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $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...
93
            $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...
94
        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
95
        //if we actually processed a row there, record it
96
        if ($job_parameters->job_size()) {
97
            $job_parameters->mark_processed(1);
98
        }
99
        return new JobStepResponse($job_parameters,
100
            __('Registrations report started successfully...', 'event_espresso'));
101
    }
102
103
104
105
    /**
106
     * Gets the filename
107
     * @return string
108
     */
109
    protected function get_filename()
110
    {
111
        return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
112
    }
113
114
115
116
    /**
117
     * Gets the questions which are to be used for this report, so they
118
     * can be remembered for later
119
     *
120
     * @param array $registration_query_params
121
     * @return array question admin labels to be used for this report
122
     */
123
    protected function _get_question_labels($registration_query_params)
124
    {
125
        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
126
        $question_query_params = array();
127
        if ($where !== null) {
128
            $question_query_params = array(
129
                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
130
            );
131
        }
132
        $question_query_params[0]['Answer.ANS_ID'] = array( 'IS_NOT_NULL' );
133
        $question_query_params['group_by'] = array( 'QST_ID' );
134
        return array_unique( \EEM_Question::instance()->get_col( $question_query_params, 'QST_admin_label' ) );
135
    }
136
137
138
139
    /**
140
     * Takes where params meant for registrations and changes them to work for questions
141
     *
142
     * @param array $reg_where_params
143
     * @return array
144
     */
145
    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
146
    {
147
        $question_where_params = array();
148
        foreach ($reg_where_params as $key => $val) {
149
            if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
150
                $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
151
            } else {
152
                //it's a normal where condition
153
                $question_where_params['Question_Group.Event.Registration.' . $key] = $val;
154
            }
155
        }
156
        return $question_where_params;
157
    }
158
159
160
161
    /**
162
     * Performs another step of the job
163
     *
164
     * @param JobParameters $job_parameters
165
     * @param int           $batch_size
166
     * @return JobStepResponse
167
     * @throws \EE_Error
168
     */
169
    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
170
    {
171
        if( $job_parameters->units_processed() < $job_parameters->job_size() ) {
172
            $csv_data = $this->get_csv_data_for($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...
173
                $job_parameters->units_processed(), $batch_size, $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...
174
                $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...
175
            \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...
176
            $units_processed = count($csv_data);
177
        }else{
178
            $units_processed = 0;
179
        }
180
        $job_parameters->mark_processed($units_processed);
181
        $extra_response_data = array(
182
            'file_url' => '',
183
        );
184 View Code Duplication
        if ($units_processed < $batch_size) {
185
            $job_parameters->set_status(JobParameters::status_complete);
186
            $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...
187
        }
188
189
        return new JobStepResponse($job_parameters,
190
            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
0 ignored issues
show
Bug introduced by
The variable $csv_data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
191
            $extra_response_data);
192
    }
193
194
195
196
    /**
197
     * Gets the csv data for a batch of registrations
198
199
     *
200
*@param int|null    $event_id
201
     * @param int   $offset
202
     * @param int   $limit
203
     * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
204
     * @param array $query_params    for using where querying the model
205
     * @return array top-level keys are numeric, next-level keys are column headers
206
     */
207
    function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
208
    {
209
        $reg_fields_to_include = array(
210
            'TXN_ID',
211
            'ATT_ID',
212
            'REG_ID',
213
            'REG_date',
214
            'REG_code',
215
            'REG_count',
216
            'REG_final_price',
217
        );
218
        $att_fields_to_include = array(
219
            'ATT_fname',
220
            'ATT_lname',
221
            'ATT_email',
222
            'ATT_address',
223
            'ATT_address2',
224
            'ATT_city',
225
            'STA_ID',
226
            'CNT_ISO',
227
            'ATT_zip',
228
            'ATT_phone',
229
        );
230
        $registrations_csv_ready_array = array();
231
        $reg_model = \EE_Registry::instance()->load_model('Registration');
232
        $query_params['limit'] = array($offset, $limit);
233
        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
234
        $registration_ids = array();
235
        foreach ($registration_rows as $reg_row) {
236
            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
237
        }
238
        foreach ($registration_rows as $reg_row) {
239
            if (is_array($reg_row)) {
240
                $reg_csv_array = array();
241 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...
242
                    //get the event's name and Id
243
                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
244
                        \EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
245
                            $reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
246
                }
247
                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
248
                /*@var $reg_row EE_Registration */
249
                foreach ($reg_fields_to_include as $field_name) {
250
                    $field = $reg_model->field_settings_for($field_name);
251
                    if ($field_name == 'REG_final_price') {
252
                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 231 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...
253
                            $reg_row['Registration.REG_final_price'], 'localized_float');
254
                    } elseif ($field_name == 'REG_count') {
255
                        $value = sprintf(__('%s of %s', 'event_espresso'),
256
                            \EEH_Export::prepare_value_from_db_for_display($reg_model, 'REG_count',
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 231 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...
257
                                $reg_row['Registration.REG_count']),
258
                            \EEH_Export::prepare_value_from_db_for_display($reg_model, '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 231 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...
259
                                $reg_row['Registration.REG_group_size']));
260
                    } elseif ($field_name == 'REG_date') {
261
                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 231 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...
262
                            $reg_row['Registration.REG_date'], 'no_html');
263
                    } else {
264
                        $value = \EEH_Export::prepare_value_from_db_for_display($reg_model, $field_name,
0 ignored issues
show
Bug introduced by
It seems like $reg_model defined by \EE_Registry::instance()...d_model('Registration') on line 231 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...
265
                            $reg_row[$field->get_qualified_column()]);
266
                    }
267
                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = $value;
268
                    if ($field_name == 'REG_final_price') {
269
                        //add a column named Currency after the final price
270
                        $reg_csv_array[__("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
271
                    }
272
                }
273
                //get pretty status
274
                $stati = \EEM_Status::instance()->localized_status(array(
275
                    $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
276
                    $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
277
                ), false, 'sentence');
278
                $reg_csv_array[__("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
279
                //get pretty transaction status
280
                $reg_csv_array[__("Transaction Status",
281
                    'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
282
                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
283
                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_total',
284
                        $reg_row['TransactionTable.TXN_total'], 'localized_float') : '0.00';
285
                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
286
                    ? \EEH_Export::prepare_value_from_db_for_display(\EEM_Transaction::instance(), 'TXN_paid',
287
                        $reg_row['TransactionTable.TXN_paid'], 'localized_float') : '0.00';
288
                $payment_methods = array();
289
                $gateway_txn_ids_etc = array();
290
                $payment_times = array();
291 View Code Duplication
                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
292
                    $payments_info = \EEM_Payment::instance()->get_all_wpdb_results(array(
293
                        array(
294
                            'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
295
                            'STS_ID' => \EEM_Payment::status_id_approved,
296
                        ),
297
                        'force_join' => array('Payment_Method'),
298
                    ), ARRAY_A,
299
                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time');
300
                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
301
                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
302
                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
303
                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
304
                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
305
                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
306
                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
307
                    }
308
                }
309
                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
310
                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
311
                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(',', $gateway_txn_ids_etc);
312
                //get whether or not the user has checked in
313
                $reg_csv_array[__("Check-Ins",
314
                    "event_espresso")] = $reg_model->count_related($reg_row['Registration.REG_ID'], 'Checkin');
315
                //get ticket of registration and its price
316
                $ticket_model = \EE_Registry::instance()->load_model('Ticket');
317
                if ($reg_row['Ticket.TKT_ID']) {
318
                    $ticket_name = \EEH_Export::prepare_value_from_db_for_display($ticket_model, 'TKT_name',
0 ignored issues
show
Bug introduced by
It seems like $ticket_model defined by \EE_Registry::instance()->load_model('Ticket') on line 316 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...
319
                        $reg_row['Ticket.TKT_name']);
320
                    $datetimes_strings = array();
321 View Code Duplication
                    foreach (
322
                        \EEM_Datetime::instance()->get_all_wpdb_results(array(
323
                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
324
                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
325
                            'default_where_conditions' => 'none',
326
                        )) as $datetime
327
                    ) {
328
                        $datetimes_strings[] = \EEH_Export::prepare_value_from_db_for_display(\EEM_Datetime::instance(),
329
                            'DTT_EVT_start', $datetime['Datetime.DTT_EVT_start']);
330
                    }
331
                } else {
332
                    $ticket_name = __('Unknown', 'event_espresso');
333
                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
334
                }
335
                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
336
                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
337
                //get datetime(s) of registration
338
                //add attendee columns
339
                foreach ($att_fields_to_include as $att_field_name) {
340
                    $field_obj = \EEM_Attendee::instance()->field_settings_for($att_field_name);
341 View Code Duplication
                    if ($reg_row['Attendee_CPT.ID']) {
342
                        if ($att_field_name == 'STA_ID') {
343
                            $value = \EEM_State::instance()
344
                                               ->get_var(array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
345
                                                   'STA_name');
346
                        } elseif ($att_field_name == 'CNT_ISO') {
347
                            $value = \EEM_Country::instance()
348
                                                 ->get_var(array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
349
                                                     'CNT_name');
350
                        } else {
351
                            $value = \EEH_Export::prepare_value_from_db_for_display(\EEM_Attendee::instance(),
352
                                $att_field_name, $reg_row[$field_obj->get_qualified_column()]);
353
                        }
354
                    } else {
355
                        $value = '';
356
                    }
357
                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field_obj)] = $value;
358
                }
359
                //make sure each registration has the same questions in the same order
360
                foreach ($question_labels as $question_label) {
361
                    if ( ! isset($reg_csv_array[$question_label])) {
362
                        $reg_csv_array[$question_label] = null;
363
                    }
364
                }
365
                $answers = \EEM_Answer::instance()->get_all_wpdb_results(array(
366
                    array('REG_ID' => $reg_row['Registration.REG_ID']),
367
                    'force_join' => array('Question'),
368
                ));
369
                //now fill out the questions THEY answered
370
                foreach ($answers as $answer_row) {
371 View Code Duplication
                    if ($answer_row['Question.QST_ID']) {
372
                        $question_label = \EEH_Export::prepare_value_from_db_for_display(\EEM_Question::instance(),
373
                            'QST_admin_label', $answer_row['Question.QST_admin_label']);
374
                    } else {
375
                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
376
                    }
377 View Code Duplication
                    if (isset($answer_row['Question.QST_type'])
378
                        && $answer_row['Question.QST_type'] == \EEM_Question::QST_type_state
379
                    ) {
380
                        $reg_csv_array[$question_label] = \EEM_State::instance()
381
                                                                    ->get_state_name_by_ID($answer_row['Answer.ANS_value']);
382
                    } else {
383
                        //this isn't for html, so don't show html entities
384
                        $reg_csv_array[$question_label] = html_entity_decode(\EEH_Export::prepare_value_from_db_for_display(\EEM_Answer::instance(),
385
                            'ANS_value', $answer_row['Answer.ANS_value']));
386
                    }
387
                }
388
                $registrations_csv_ready_array[] = apply_filters('FHEE__EE_Export__report_registrations__reg_csv_array',
389
                    $reg_csv_array, $reg_row);
390
            }
391
        }
392
        //if we couldn't export anything, we want to at least show the column headers
393 View Code Duplication
        if (empty($registrations_csv_ready_array)) {
394
            $reg_csv_array = array();
395
            $model_and_fields_to_include = array(
396
                'Registration' => $reg_fields_to_include,
397
                'Attendee'     => $att_fields_to_include,
398
            );
399
            foreach ($model_and_fields_to_include as $model_name => $field_list) {
400
                $model = \EE_Registry::instance()->load_model($model_name);
401
                foreach ($field_list as $field_name) {
402
                    $field = $model->field_settings_for($field_name);
403
                    $reg_csv_array[\EEH_Export::get_column_name_for_field($field)] = null;
404
                }
405
            }
406
            $registrations_csv_ready_array[] = $reg_csv_array;
407
        }
408
        return $registrations_csv_ready_array;
409
    }
410
411
412
413
    /**
414
     * Counts total unit to process
415
     *
416
     * @deprecated since 4.9.19
417
     * @param int|array $event_id
418
     * @return int
419
     */
420
    public function count_units_to_process($event_id)
421
    {
422
        //use the legacy filter
423 View Code Duplication
        if ($event_id) {
424
            $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...
425
        } else {
426
            $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...
427
        }
428
        return \EEM_Registration::instance()->count($query_params);
429
    }
430
431
432
433
    /**
434
     * Performs any clean-up logic when we know the job is completed.
435
     * In this case, we delete the temporary file
436
     *
437
     * @param JobParameters $job_parameters
438
     * @return boolean
439
     */
440
    public function cleanup_job(JobParameters $job_parameters)
441
    {
442
        $this->_file_helper->delete(\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...
443
            true, 'd');
444
        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
445
    }
446
}
447
448
449