Completed
Branch FET-8385-datetime-ticket-selec... (cac7e5)
by
unknown
67:23 queued 43:13
created

RegistrationsReport   F

Complexity

Total Complexity 48

Size/Duplication

Total Lines 405
Duplicated Lines 25.19 %

Coupling/Cohesion

Components 2
Dependencies 22

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 102
loc 405
rs 3.894
c 1
b 0
f 0
wmc 48
lcom 2
cbo 22

7 Methods

Rating   Name   Duplication   Size   Complexity  
A create_job() 0 22 3
A get_filename_from_event() 8 12 3
A _get_questions_for_report() 0 13 2
A continue_job() 4 18 2
F get_csv_data_for() 85 229 35
B count_units_to_process() 5 30 2
A cleanup_job() 0 6 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
 * 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_from_event($event_id));
45
        $job_parameters->add_extra_data('filepath', $filepath);
46
        $question_data_for_columns = $this->_get_questions_for_report($event_id);
47
        $job_parameters->add_extra_data('questions_data', $question_data_for_columns);
48
        $job_parameters->set_job_size($this->count_units_to_process($event_id));
49
        //we should also set the header columns
50
        $csv_data_for_row = $this->get_csv_data_for($event_id, 0, 1, $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...
51
        \EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
52
        //if we actually processed a row there, record it
53
        if ($job_parameters->job_size()) {
54
            $job_parameters->mark_processed(1);
55
        }
56
        return new JobStepResponse($job_parameters,
57
            __('Registrations report started successfully...', 'event_espresso'));
58
    }
59
60
61
62
    /**
63
     * Creates teh filename form the event id (or lack thereof)
64
     *
65
     * @param int $event_id
66
     * @return string
67
     */
68
    protected function get_filename_from_event($event_id)
69
    {
70 View Code Duplication
        if ($event_id) {
71
            $event_slug = \EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
72
            if ( ! $event_slug) {
73
                $event_slug = __('unknown', 'event_espresso');
74
            }
75
        } else {
76
            $event_slug = __('all', 'event_espresso');
77
        }
78
        return sprintf("registrations-for-%s.csv", $event_slug);
79
    }
80
81
82
83
    /**
84
     * Gets the questions which are to be used for this report, so they
85
     * can be remembered for later
86
     *
87
     * @param int|null $event_id
88
     * @return array of wpdb results for questions which are to be used for this report
89
     */
90
    protected function _get_questions_for_report($event_id)
91
    {
92
        $question_query_params = array(
93
            array(
94
                'Answer.ANS_ID' => array('IS_NOT_NULL'),
95
            ),
96
            'group_by' => array('QST_ID'),
97
        );
98
        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...
99
            $question_query_params[0]['Answer.Registration.EVT_ID'] = $event_id;
100
        }
101
        return \EEM_Question::instance()->get_all_wpdb_results($question_query_params);
102
    }
103
104
105
106
    /**
107
     * Performs another step of the job
108
     *
109
     * @param JobParameters $job_parameters
110
     * @param int           $batch_size
111
     * @return JobStepResponse
112
     * @throws \EE_Error
113
     */
114
    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
115
    {
116
        $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...
117
            $job_parameters->units_processed(), $batch_size, $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...
118
        \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...
119
        $units_processed = count($csv_data);
120
        $job_parameters->mark_processed($units_processed);
121
        $extra_response_data = array(
122
            'file_url' => '',
123
        );
124 View Code Duplication
        if ($units_processed < $batch_size) {
125
            $job_parameters->set_status(JobParameters::status_complete);
126
            $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...
127
        }
128
        return new JobStepResponse($job_parameters,
129
            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count($csv_data)),
130
            $extra_response_data);
131
    }
132
133
134
135
    /**
136
     * Gets the csv data for a batch of registrations
137
     *
138
     * @param int|null $event_id
139
     * @param int      $offset
140
     * @param int      $limit
141
     * @param array    $questions_for_these_regs_rows results of $wpdb->get_results( $something, ARRAY_A) when querying
142
     *                                                for questions
143
     * @return array top-level keys are numeric, next-level keys are column headers
144
     */
145
    function get_csv_data_for($event_id, $offset, $limit, $questions_for_these_regs_rows)
146
    {
147
        $reg_fields_to_include = array(
148
            'TXN_ID',
149
            'ATT_ID',
150
            'REG_ID',
151
            'REG_date',
152
            'REG_code',
153
            'REG_count',
154
            'REG_final_price',
155
        );
156
        $att_fields_to_include = array(
157
            'ATT_fname',
158
            'ATT_lname',
159
            'ATT_email',
160
            'ATT_address',
161
            'ATT_address2',
162
            'ATT_city',
163
            'STA_ID',
164
            'CNT_ISO',
165
            'ATT_zip',
166
            'ATT_phone',
167
        );
168
        $registrations_csv_ready_array = array();
169
        $reg_model = \EE_Registry::instance()->load_model('Registration');
170
        $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
171
                array(
172
                    'OR'                 => array(
173
                        //don't include registrations from failed or abandoned transactions...
174
                        'Transaction.STS_ID' => array(
175
                            'NOT IN',
176
                            array(
177
                                \EEM_Transaction::failed_status_code,
178
                                \EEM_Transaction::abandoned_status_code,
179
                            ),
180
                        ),
181
                        //unless the registration is approved, in which case include it regardless of transaction status
182
                        'STS_ID'             => \EEM_Registration::status_id_approved,
183
                    ),
184
                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
185
                ),
186
                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
187
                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
188
                'limit'      => array($offset, $limit),
189
                'caps'       => \EEM_Base::caps_read_admin,
190
            ), $event_id);
191 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...
192
            $query_params[0]['EVT_ID'] = $event_id;
193
        } else {
194
            $query_params['force_join'][] = 'Event';
195
        }
196
        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
197
        //get all questions which relate to someone in this group
198
        $registration_ids = array();
199
        foreach ($registration_rows as $reg_row) {
200
            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
201
        }
202
        foreach ($registration_rows as $reg_row) {
203
            if (is_array($reg_row)) {
204
                $reg_csv_array = array();
205 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...
206
                    //get the event's name and Id
207
                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(__('%1$s (%2$s)', 'event_espresso'),
208
                        \EEH_Export::prepare_value_from_db_for_display(\EEM_Event::instance(), 'EVT_name',
209
                            $reg_row['Event_CPT.post_title']), $reg_row['Event_CPT.ID']);
210
                }
211
                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
212
                /*@var $reg_row EE_Registration */
213
                foreach ($reg_fields_to_include as $field_name) {
214
                    $field = $reg_model->field_settings_for($field_name);
215
                    if ($field_name == 'REG_final_price') {
216
                        $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 169 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...
217
                            $reg_row['Registration.REG_final_price'], 'localized_float');
218
                    } elseif ($field_name == 'REG_count') {
219
                        $value = sprintf(__('%s of %s', 'event_espresso'),
220
                            \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 169 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
221
                                $reg_row['Registration.REG_count']),
222
                            \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 169 can be null; however, EEH_Export::prepare_value_from_db_for_display() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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