Completed
Branch Gutenberg/model-select-folders (c9f0f6)
by
unknown
83:44 queued 74:33
created
core/helpers/EEH_Line_Item.helper.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
      * Deletes ALL children of the passed line item
875 875
      *
876 876
      * @param EE_Line_Item $parent_line_item
877
-     * @return bool
877
+     * @return integer
878 878
      * @throws \EE_Error
879 879
      */
880 880
     public static function delete_all_child_items(EE_Line_Item $parent_line_item)
@@ -1138,6 +1138,7 @@  discard block
 block discarded – undo
1138 1138
      * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1139 1139
      * @param string $line_item_type one of the EEM_Line_Item constants
1140 1140
      * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1141
+     * @param string $obj_type
1141 1142
      * @return EE_Line_Item[]
1142 1143
      */
1143 1144
     protected static function _get_descendants_by_type_and_object_type(
Please login to merge, or discard this patch.
Indentation   +1685 added lines, -1685 removed lines patch added patch discarded remove patch
@@ -20,1689 +20,1689 @@
 block discarded – undo
20 20
 class EEH_Line_Item
21 21
 {
22 22
 
23
-    // other functions: cancel ticket purchase
24
-    // delete ticket purchase
25
-    // add promotion
26
-
27
-
28
-    /**
29
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
30
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
31
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
32
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
33
-     * to keep the registration final prices in-sync with the transaction's total.
34
-     *
35
-     * @param EE_Line_Item $parent_line_item
36
-     * @param string $name
37
-     * @param float $unit_price
38
-     * @param string $description
39
-     * @param int $quantity
40
-     * @param boolean $taxable
41
-     * @param boolean $code if set to a value, ensures there is only one line item with that code
42
-     * @return boolean success
43
-     * @throws \EE_Error
44
-     */
45
-    public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = false, $code = null)
46
-    {
47
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
48
-        $line_item = EE_Line_Item::new_instance(array(
49
-            'LIN_name' => $name,
50
-            'LIN_desc' => $description,
51
-            'LIN_unit_price' => $unit_price,
52
-            'LIN_quantity' => $quantity,
53
-            'LIN_percent' => null,
54
-            'LIN_is_taxable' => $taxable,
55
-            'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
56
-            'LIN_total' => (float) $unit_price * (int) $quantity,
57
-            'LIN_type' => EEM_Line_Item::type_line_item,
58
-            'LIN_code' => $code,
59
-        ));
60
-        $line_item = apply_filters(
61
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
62
-            $line_item,
63
-            $parent_line_item
64
-        );
65
-        return self::add_item($parent_line_item, $line_item);
66
-    }
67
-
68
-
69
-    /**
70
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
71
-     * in the correct spot in the line item tree. Automatically
72
-     * re-calculates the line item totals and updates the related transaction. But
73
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
74
-     * should probably change because of this).
75
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
76
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
77
-     *
78
-     * @param EE_Line_Item $parent_line_item
79
-     * @param string $name
80
-     * @param float $percentage_amount
81
-     * @param string $description
82
-     * @param boolean $taxable
83
-     * @return boolean success
84
-     * @throws \EE_Error
85
-     */
86
-    public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = false)
87
-    {
88
-        $line_item = EE_Line_Item::new_instance(array(
89
-            'LIN_name' => $name,
90
-            'LIN_desc' => $description,
91
-            'LIN_unit_price' => 0,
92
-            'LIN_percent' => $percentage_amount,
93
-            'LIN_quantity' => 1,
94
-            'LIN_is_taxable' => $taxable,
95
-            'LIN_total' => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
96
-            'LIN_type' => EEM_Line_Item::type_line_item,
97
-            'LIN_parent' => $parent_line_item->ID()
98
-        ));
99
-        $line_item = apply_filters(
100
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
101
-            $line_item
102
-        );
103
-        return $parent_line_item->add_child_line_item($line_item, false);
104
-    }
105
-
106
-
107
-    /**
108
-     * Returns the new line item created by adding a purchase of the ticket
109
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
110
-     * If this ticket has already been purchased, just increments its count.
111
-     * Automatically re-calculates the line item totals and updates the related transaction. But
112
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
113
-     * should probably change because of this).
114
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
115
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
116
-     *
117
-     * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
118
-     * @param EE_Ticket $ticket
119
-     * @param int $qty
120
-     * @return \EE_Line_Item
121
-     * @throws \EE_Error
122
-     */
123
-    public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
124
-    {
125
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
126
-            throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
127
-        }
128
-        // either increment the qty for an existing ticket
129
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
130
-        // or add a new one
131
-        if (!$line_item instanceof EE_Line_Item) {
132
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
133
-        }
134
-        $total_line_item->recalculate_total_including_taxes();
135
-        return $line_item;
136
-    }
137
-
138
-
139
-    /**
140
-     * Returns the new line item created by adding a purchase of the ticket
141
-     * @param \EE_Line_Item $total_line_item
142
-     * @param EE_Ticket $ticket
143
-     * @param int $qty
144
-     * @return \EE_Line_Item
145
-     * @throws \EE_Error
146
-     */
147
-    public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
148
-    {
149
-        $line_item = null;
150
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
151
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
152
-            foreach ((array) $ticket_line_items as $ticket_line_item) {
153
-                if ($ticket_line_item instanceof EE_Line_Item
154
-                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
155
-                ) {
156
-                    $line_item = $ticket_line_item;
157
-                    break;
158
-                }
159
-            }
160
-        }
161
-        if ($line_item instanceof EE_Line_Item) {
162
-            EEH_Line_Item::increment_quantity($line_item, $qty);
163
-            return $line_item;
164
-        }
165
-        return null;
166
-    }
167
-
168
-
169
-    /**
170
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
171
-     * Does NOT save or recalculate other line items totals
172
-     *
173
-     * @param EE_Line_Item $line_item
174
-     * @param int $qty
175
-     * @return void
176
-     * @throws \EE_Error
177
-     */
178
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
179
-    {
180
-        if (!$line_item->is_percent()) {
181
-            $qty += $line_item->quantity();
182
-            $line_item->set_quantity($qty);
183
-            $line_item->set_total($line_item->unit_price() * $qty);
184
-            $line_item->save();
185
-        }
186
-        foreach ($line_item->children() as $child) {
187
-            if ($child->is_sub_line_item()) {
188
-                EEH_Line_Item::update_quantity($child, $qty);
189
-            }
190
-        }
191
-    }
192
-
193
-
194
-    /**
195
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
196
-     * Does NOT save or recalculate other line items totals
197
-     *
198
-     * @param EE_Line_Item $line_item
199
-     * @param int $qty
200
-     * @return void
201
-     * @throws \EE_Error
202
-     */
203
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
204
-    {
205
-        if (!$line_item->is_percent()) {
206
-            $qty = $line_item->quantity() - $qty;
207
-            $qty = max($qty, 0);
208
-            $line_item->set_quantity($qty);
209
-            $line_item->set_total($line_item->unit_price() * $qty);
210
-            $line_item->save();
211
-        }
212
-        foreach ($line_item->children() as $child) {
213
-            if ($child->is_sub_line_item()) {
214
-                EEH_Line_Item::update_quantity($child, $qty);
215
-            }
216
-        }
217
-    }
218
-
219
-
220
-    /**
221
-     * Updates the line item and its children's quantities to the specified number.
222
-     * Does NOT save them or recalculate totals.
223
-     *
224
-     * @param EE_Line_Item $line_item
225
-     * @param int $new_quantity
226
-     * @throws \EE_Error
227
-     */
228
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
229
-    {
230
-        if (!$line_item->is_percent()) {
231
-            $line_item->set_quantity($new_quantity);
232
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
233
-            $line_item->save();
234
-        }
235
-        foreach ($line_item->children() as $child) {
236
-            if ($child->is_sub_line_item()) {
237
-                EEH_Line_Item::update_quantity($child, $new_quantity);
238
-            }
239
-        }
240
-    }
241
-
242
-
243
-    /**
244
-     * Returns the new line item created by adding a purchase of the ticket
245
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
246
-     * @param EE_Ticket $ticket
247
-     * @param int $qty
248
-     * @return \EE_Line_Item
249
-     * @throws \EE_Error
250
-     */
251
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
252
-    {
253
-        $datetimes = $ticket->datetimes();
254
-        $first_datetime = reset($datetimes);
255
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
256
-            $first_datetime_name = $first_datetime->event()->name();
257
-        } else {
258
-            $first_datetime_name = __('Event', 'event_espresso');
259
-        }
260
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
261
-        // get event subtotal line
262
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
263
-        // add $ticket to cart
264
-        $line_item = EE_Line_Item::new_instance(array(
265
-            'LIN_name' => $ticket->name(),
266
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
267
-            'LIN_unit_price' => $ticket->price(),
268
-            'LIN_quantity' => $qty,
269
-            'LIN_is_taxable' => $ticket->taxable(),
270
-            'LIN_order' => count($events_sub_total->children()),
271
-            'LIN_total' => $ticket->price() * $qty,
272
-            'LIN_type' => EEM_Line_Item::type_line_item,
273
-            'OBJ_ID' => $ticket->ID(),
274
-            'OBJ_type' => 'Ticket'
275
-        ));
276
-        $line_item = apply_filters(
277
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
278
-            $line_item
279
-        );
280
-        $events_sub_total->add_child_line_item($line_item);
281
-        // now add the sub-line items
282
-        $running_total_for_ticket = 0;
283
-        foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
284
-            $sign = $price->is_discount() ? -1 : 1;
285
-            $price_total = $price->is_percent()
286
-                ? $running_total_for_ticket * $price->amount() / 100
287
-                : $price->amount() * $qty;
288
-            $sub_line_item = EE_Line_Item::new_instance(array(
289
-                'LIN_name' => $price->name(),
290
-                'LIN_desc' => $price->desc(),
291
-                'LIN_quantity' => $price->is_percent() ? null : $qty,
292
-                'LIN_is_taxable' => false,
293
-                'LIN_order' => $price->order(),
294
-                'LIN_total' => $sign * $price_total,
295
-                'LIN_type' => EEM_Line_Item::type_sub_line_item,
296
-                'OBJ_ID' => $price->ID(),
297
-                'OBJ_type' => 'Price'
298
-            ));
299
-            $sub_line_item = apply_filters(
300
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
301
-                $sub_line_item
302
-            );
303
-            if ($price->is_percent()) {
304
-                $sub_line_item->set_percent($sign * $price->amount());
305
-            } else {
306
-                $sub_line_item->set_unit_price($sign * $price->amount());
307
-            }
308
-            $running_total_for_ticket += $price_total;
309
-            $line_item->add_child_line_item($sub_line_item);
310
-        }
311
-        return $line_item;
312
-    }
313
-
314
-
315
-    /**
316
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
317
-     * re-calculates the line item totals and updates the related transaction. But
318
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
319
-     * should probably change because of this).
320
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
321
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
322
-     *
323
-     * @param EE_Line_Item $total_line_item
324
-     * @param EE_Line_Item $item to be added
325
-     * @return boolean
326
-     * @throws \EE_Error
327
-     */
328
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
329
-    {
330
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
331
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
332
-            $success = $pre_tax_subtotal->add_child_line_item($item);
333
-        } else {
334
-            return false;
335
-        }
336
-        $total_line_item->recalculate_total_including_taxes();
337
-        return $success;
338
-    }
339
-
340
-
341
-    /**
342
-     * cancels an existing ticket line item,
343
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
344
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
345
-     *
346
-     * @param EE_Line_Item $ticket_line_item
347
-     * @param int $qty
348
-     * @return bool success
349
-     * @throws \EE_Error
350
-     */
351
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
352
-    {
353
-        // validate incoming line_item
354
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
355
-            throw new EE_Error(
356
-                sprintf(
357
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
358
-                    $ticket_line_item->type()
359
-                )
360
-            );
361
-        }
362
-        if ($ticket_line_item->quantity() < $qty) {
363
-            throw new EE_Error(
364
-                sprintf(
365
-                    __('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
366
-                    $qty,
367
-                    $ticket_line_item->quantity()
368
-                )
369
-            );
370
-        }
371
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
372
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
373
-        foreach ($ticket_line_item->children() as $child_line_item) {
374
-            if ($child_line_item->is_sub_line_item()
375
-                && !$child_line_item->is_percent()
376
-                && !$child_line_item->is_cancellation()
377
-            ) {
378
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
379
-            }
380
-        }
381
-        // get cancellation sub line item
382
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
383
-            $ticket_line_item,
384
-            EEM_Line_Item::type_cancellation
385
-        );
386
-        $cancellation_line_item = reset($cancellation_line_item);
387
-        // verify that this ticket was indeed previously cancelled
388
-        if ($cancellation_line_item instanceof EE_Line_Item) {
389
-            // increment cancelled quantity
390
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
391
-        } else {
392
-            // create cancellation sub line item
393
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
394
-                'LIN_name' => __('Cancellation', 'event_espresso'),
395
-                'LIN_desc' => sprintf(
396
-                    _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
397
-                    $ticket_line_item->name(),
398
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
399
-                ),
400
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
401
-                'LIN_quantity' => $qty,
402
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
403
-                'LIN_order' => count($ticket_line_item->children()),
404
-                'LIN_total' => 0, // $ticket_line_item->unit_price()
405
-                'LIN_type' => EEM_Line_Item::type_cancellation,
406
-            ));
407
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
408
-        }
409
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
410
-            // decrement parent line item quantity
411
-            $event_line_item = $ticket_line_item->parent();
412
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
413
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
414
-                $event_line_item->save();
415
-            }
416
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
417
-            return true;
418
-        }
419
-        return false;
420
-    }
421
-
422
-
423
-    /**
424
-     * reinstates (un-cancels?) a previously canceled ticket line item,
425
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
426
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
427
-     *
428
-     * @param EE_Line_Item $ticket_line_item
429
-     * @param int $qty
430
-     * @return bool success
431
-     * @throws \EE_Error
432
-     */
433
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
434
-    {
435
-        // validate incoming line_item
436
-        if ($ticket_line_item->OBJ_type() !== 'Ticket') {
437
-            throw new EE_Error(
438
-                sprintf(
439
-                    __('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
440
-                    $ticket_line_item->type()
441
-                )
442
-            );
443
-        }
444
-        // get cancellation sub line item
445
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
446
-            $ticket_line_item,
447
-            EEM_Line_Item::type_cancellation
448
-        );
449
-        $cancellation_line_item = reset($cancellation_line_item);
450
-        // verify that this ticket was indeed previously cancelled
451
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
452
-            return false;
453
-        }
454
-        if ($cancellation_line_item->quantity() > $qty) {
455
-            // decrement cancelled quantity
456
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
457
-        } elseif ($cancellation_line_item->quantity() == $qty) {
458
-            // decrement cancelled quantity in case anyone still has the object kicking around
459
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
460
-            // delete because quantity will end up as 0
461
-            $cancellation_line_item->delete();
462
-            // and attempt to destroy the object,
463
-            // even though PHP won't actually destroy it until it needs the memory
464
-            unset($cancellation_line_item);
465
-        } else {
466
-            // what ?!?! negative quantity ?!?!
467
-            throw new EE_Error(
468
-                sprintf(
469
-                    __(
470
-                        'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
471
-                        'event_espresso'
472
-                    ),
473
-                    $qty,
474
-                    $cancellation_line_item->quantity()
475
-                )
476
-            );
477
-        }
478
-        // increment ticket quantity
479
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
480
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
481
-            // increment parent line item quantity
482
-            $event_line_item = $ticket_line_item->parent();
483
-            if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
484
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
485
-            }
486
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
487
-            return true;
488
-        }
489
-        return false;
490
-    }
491
-
492
-
493
-    /**
494
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
495
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
496
-     *
497
-     * @param EE_Line_Item $line_item
498
-     * @return \EE_Line_Item
499
-     */
500
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
501
-    {
502
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
503
-        return $grand_total_line_item->recalculate_total_including_taxes();
504
-    }
505
-
506
-
507
-    /**
508
-     * Gets the line item which contains the subtotal of all the items
509
-     *
510
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
511
-     * @return \EE_Line_Item
512
-     * @throws \EE_Error
513
-     */
514
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
515
-    {
516
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
517
-        return $pre_tax_subtotal instanceof EE_Line_Item
518
-            ? $pre_tax_subtotal
519
-            : self::create_pre_tax_subtotal($total_line_item);
520
-    }
521
-
522
-
523
-    /**
524
-     * Gets the line item for the taxes subtotal
525
-     *
526
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
527
-     * @return \EE_Line_Item
528
-     * @throws \EE_Error
529
-     */
530
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
531
-    {
532
-        $taxes = $total_line_item->get_child_line_item('taxes');
533
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
534
-    }
535
-
536
-
537
-    /**
538
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
539
-     *
540
-     * @param EE_Line_Item $line_item
541
-     * @param EE_Transaction $transaction
542
-     * @return void
543
-     * @throws \EE_Error
544
-     */
545
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
546
-    {
547
-        if ($transaction) {
548
-            /** @type EEM_Transaction $EEM_Transaction */
549
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
550
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
551
-            $line_item->set_TXN_ID($TXN_ID);
552
-        }
553
-    }
554
-
555
-
556
-    /**
557
-     * Creates a new default total line item for the transaction,
558
-     * and its tickets subtotal and taxes subtotal line items (and adds the
559
-     * existing taxes as children of the taxes subtotal line item)
560
-     *
561
-     * @param EE_Transaction $transaction
562
-     * @return \EE_Line_Item of type total
563
-     * @throws \EE_Error
564
-     */
565
-    public static function create_total_line_item($transaction = null)
566
-    {
567
-        $total_line_item = EE_Line_Item::new_instance(array(
568
-            'LIN_code' => 'total',
569
-            'LIN_name' => __('Grand Total', 'event_espresso'),
570
-            'LIN_type' => EEM_Line_Item::type_total,
571
-            'OBJ_type' => 'Transaction'
572
-        ));
573
-        $total_line_item = apply_filters(
574
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
575
-            $total_line_item
576
-        );
577
-        self::set_TXN_ID($total_line_item, $transaction);
578
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
579
-        self::create_taxes_subtotal($total_line_item, $transaction);
580
-        return $total_line_item;
581
-    }
582
-
583
-
584
-    /**
585
-     * Creates a default items subtotal line item
586
-     *
587
-     * @param EE_Line_Item $total_line_item
588
-     * @param EE_Transaction $transaction
589
-     * @return EE_Line_Item
590
-     * @throws \EE_Error
591
-     */
592
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
593
-    {
594
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
595
-            'LIN_code' => 'pre-tax-subtotal',
596
-            'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
597
-            'LIN_type' => EEM_Line_Item::type_sub_total
598
-        ));
599
-        $pre_tax_line_item = apply_filters(
600
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
601
-            $pre_tax_line_item
602
-        );
603
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
604
-        $total_line_item->add_child_line_item($pre_tax_line_item);
605
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
606
-        return $pre_tax_line_item;
607
-    }
608
-
609
-
610
-    /**
611
-     * Creates a line item for the taxes subtotal and finds all the tax prices
612
-     * and applies taxes to it
613
-     *
614
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
615
-     * @param EE_Transaction $transaction
616
-     * @return EE_Line_Item
617
-     * @throws \EE_Error
618
-     */
619
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
620
-    {
621
-        $tax_line_item = EE_Line_Item::new_instance(array(
622
-            'LIN_code' => 'taxes',
623
-            'LIN_name' => __('Taxes', 'event_espresso'),
624
-            'LIN_type' => EEM_Line_Item::type_tax_sub_total,
625
-            'LIN_order' => 1000,// this should always come last
626
-        ));
627
-        $tax_line_item = apply_filters(
628
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
629
-            $tax_line_item
630
-        );
631
-        self::set_TXN_ID($tax_line_item, $transaction);
632
-        $total_line_item->add_child_line_item($tax_line_item);
633
-        // and lastly, add the actual taxes
634
-        self::apply_taxes($total_line_item);
635
-        return $tax_line_item;
636
-    }
637
-
638
-
639
-    /**
640
-     * Creates a default items subtotal line item
641
-     *
642
-     * @param EE_Line_Item $pre_tax_line_item
643
-     * @param EE_Transaction $transaction
644
-     * @param EE_Event $event
645
-     * @return EE_Line_Item
646
-     * @throws \EE_Error
647
-     */
648
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
649
-    {
650
-        $event_line_item = EE_Line_Item::new_instance(array(
651
-            'LIN_code' => self::get_event_code($event),
652
-            'LIN_name' => self::get_event_name($event),
653
-            'LIN_desc' => self::get_event_desc($event),
654
-            'LIN_type' => EEM_Line_Item::type_sub_total,
655
-            'OBJ_type' => 'Event',
656
-            'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
657
-        ));
658
-        $event_line_item = apply_filters(
659
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
660
-            $event_line_item
661
-        );
662
-        self::set_TXN_ID($event_line_item, $transaction);
663
-        $pre_tax_line_item->add_child_line_item($event_line_item);
664
-        return $event_line_item;
665
-    }
666
-
667
-
668
-    /**
669
-     * Gets what the event ticket's code SHOULD be
670
-     *
671
-     * @param EE_Event $event
672
-     * @return string
673
-     * @throws \EE_Error
674
-     */
675
-    public static function get_event_code($event)
676
-    {
677
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
678
-    }
679
-
680
-    /**
681
-     * Gets the event name
682
-     * @param EE_Event $event
683
-     * @return string
684
-     */
685
-    public static function get_event_name($event)
686
-    {
687
-        return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
688
-    }
689
-
690
-    /**
691
-     * Gets the event excerpt
692
-     * @param EE_Event $event
693
-     * @return string
694
-     */
695
-    public static function get_event_desc($event)
696
-    {
697
-        return $event instanceof EE_Event ? $event->short_description() : '';
698
-    }
699
-
700
-    /**
701
-     * Given the grand total line item and a ticket, finds the event sub-total
702
-     * line item the ticket's purchase should be added onto
703
-     *
704
-     * @access public
705
-     * @param EE_Line_Item $grand_total the grand total line item
706
-     * @param EE_Ticket $ticket
707
-     * @throws \EE_Error
708
-     * @return EE_Line_Item
709
-     */
710
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
711
-    {
712
-        $first_datetime = $ticket->first_datetime();
713
-        if (!$first_datetime instanceof EE_Datetime) {
714
-            throw new EE_Error(
715
-                sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
716
-            );
717
-        }
718
-        $event = $first_datetime->event();
719
-        if (!$event instanceof EE_Event) {
720
-            throw new EE_Error(
721
-                sprintf(
722
-                    __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
723
-                    $ticket->ID()
724
-                )
725
-            );
726
-        }
727
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
728
-        if (!$events_sub_total instanceof EE_Line_Item) {
729
-            throw new EE_Error(
730
-                sprintf(
731
-                    __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
732
-                    $ticket->ID(),
733
-                    $grand_total->ID()
734
-                )
735
-            );
736
-        }
737
-        return $events_sub_total;
738
-    }
739
-
740
-
741
-    /**
742
-     * Gets the event line item
743
-     *
744
-     * @param EE_Line_Item $grand_total
745
-     * @param EE_Event $event
746
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
747
-     * @throws \EE_Error
748
-     */
749
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
750
-    {
751
-        /** @type EE_Event $event */
752
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
753
-        $event_line_item = null;
754
-        $found = false;
755
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
756
-            // default event subtotal, we should only ever find this the first time this method is called
757
-            if (!$event_line_item->OBJ_ID()) {
758
-                // let's use this! but first... set the event details
759
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
760
-                $found = true;
761
-                break;
762
-            } elseif ($event_line_item->OBJ_ID() === $event->ID()) {
763
-                // found existing line item for this event in the cart, so break out of loop and use this one
764
-                $found = true;
765
-                break;
766
-            }
767
-        }
768
-        if (!$found) {
769
-            // there is no event sub-total yet, so add it
770
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
771
-            // create a new "event" subtotal below that
772
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
773
-            // and set the event details
774
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
775
-        }
776
-        return $event_line_item;
777
-    }
778
-
779
-
780
-    /**
781
-     * Creates a default items subtotal line item
782
-     *
783
-     * @param EE_Line_Item $event_line_item
784
-     * @param EE_Event $event
785
-     * @param EE_Transaction $transaction
786
-     * @return EE_Line_Item
787
-     * @throws \EE_Error
788
-     */
789
-    public static function set_event_subtotal_details(
790
-        EE_Line_Item $event_line_item,
791
-        EE_Event $event,
792
-        $transaction = null
793
-    ) {
794
-        if ($event instanceof EE_Event) {
795
-            $event_line_item->set_code(self::get_event_code($event));
796
-            $event_line_item->set_name(self::get_event_name($event));
797
-            $event_line_item->set_desc(self::get_event_desc($event));
798
-            $event_line_item->set_OBJ_ID($event->ID());
799
-        }
800
-        self::set_TXN_ID($event_line_item, $transaction);
801
-    }
802
-
803
-
804
-    /**
805
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
806
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
807
-     * any old taxes are removed
808
-     *
809
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
810
-     * @throws \EE_Error
811
-     */
812
-    public static function apply_taxes(EE_Line_Item $total_line_item)
813
-    {
814
-        /** @type EEM_Price $EEM_Price */
815
-        $EEM_Price = EE_Registry::instance()->load_model('Price');
816
-        // get array of taxes via Price Model
817
-        $ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
818
-        ksort($ordered_taxes);
819
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
820
-        // just to be safe, remove its old tax line items
821
-        $taxes_line_item->delete_children_line_items();
822
-        // loop thru taxes
823
-        foreach ($ordered_taxes as $order => $taxes) {
824
-            foreach ($taxes as $tax) {
825
-                if ($tax instanceof EE_Price) {
826
-                    $tax_line_item = EE_Line_Item::new_instance(
827
-                        array(
828
-                            'LIN_name' => $tax->name(),
829
-                            'LIN_desc' => $tax->desc(),
830
-                            'LIN_percent' => $tax->amount(),
831
-                            'LIN_is_taxable' => false,
832
-                            'LIN_order' => $order,
833
-                            'LIN_total' => 0,
834
-                            'LIN_type' => EEM_Line_Item::type_tax,
835
-                            'OBJ_type' => 'Price',
836
-                            'OBJ_ID' => $tax->ID()
837
-                        )
838
-                    );
839
-                    $tax_line_item = apply_filters(
840
-                        'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
841
-                        $tax_line_item
842
-                    );
843
-                    $taxes_line_item->add_child_line_item($tax_line_item);
844
-                }
845
-            }
846
-        }
847
-        $total_line_item->recalculate_total_including_taxes();
848
-    }
849
-
850
-
851
-    /**
852
-     * Ensures that taxes have been applied to the order, if not applies them.
853
-     * Returns the total amount of tax
854
-     *
855
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
856
-     * @return float
857
-     * @throws \EE_Error
858
-     */
859
-    public static function ensure_taxes_applied($total_line_item)
860
-    {
861
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
862
-        if (!$taxes_subtotal->children()) {
863
-            self::apply_taxes($total_line_item);
864
-        }
865
-        return $taxes_subtotal->total();
866
-    }
867
-
868
-
869
-    /**
870
-     * Deletes ALL children of the passed line item
871
-     *
872
-     * @param EE_Line_Item $parent_line_item
873
-     * @return bool
874
-     * @throws \EE_Error
875
-     */
876
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
877
-    {
878
-        $deleted = 0;
879
-        foreach ($parent_line_item->children() as $child_line_item) {
880
-            if ($child_line_item instanceof EE_Line_Item) {
881
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
882
-                if ($child_line_item->ID()) {
883
-                    $child_line_item->delete();
884
-                    unset($child_line_item);
885
-                } else {
886
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
887
-                }
888
-                $deleted++;
889
-            }
890
-        }
891
-        return $deleted;
892
-    }
893
-
894
-
895
-    /**
896
-     * Deletes the line items as indicated by the line item code(s) provided,
897
-     * regardless of where they're found in the line item tree. Automatically
898
-     * re-calculates the line item totals and updates the related transaction. But
899
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
900
-     * should probably change because of this).
901
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
902
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
903
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
904
-     * @param array|bool|string $line_item_codes
905
-     * @return int number of items successfully removed
906
-     */
907
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
908
-    {
909
-
910
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
911
-            EE_Error::doing_it_wrong(
912
-                'EEH_Line_Item::delete_items',
913
-                __(
914
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
915
-                    'event_espresso'
916
-                ),
917
-                '4.6.18'
918
-            );
919
-        }
920
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
921
-
922
-        // check if only a single line_item_id was passed
923
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
924
-            // place single line_item_id in an array to appear as multiple line_item_ids
925
-            $line_item_codes = array($line_item_codes);
926
-        }
927
-        $removals = 0;
928
-        // cycle thru line_item_ids
929
-        foreach ($line_item_codes as $line_item_id) {
930
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
931
-        }
932
-
933
-        if ($removals > 0) {
934
-            $total_line_item->recalculate_taxes_and_tax_total();
935
-            return $removals;
936
-        } else {
937
-            return false;
938
-        }
939
-    }
940
-
941
-
942
-    /**
943
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
944
-     * tax and updates the total line item accordingly
945
-     *
946
-     * @param EE_Line_Item $total_line_item
947
-     * @param float $amount
948
-     * @param string $name
949
-     * @param string $description
950
-     * @param string $code
951
-     * @param boolean $add_to_existing_line_item
952
-     *                          if true, and a duplicate line item with the same code is found,
953
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
954
-     * @return EE_Line_Item the new tax line item created
955
-     * @throws \EE_Error
956
-     */
957
-    public static function set_total_tax_to(
958
-        EE_Line_Item $total_line_item,
959
-        $amount,
960
-        $name = null,
961
-        $description = null,
962
-        $code = null,
963
-        $add_to_existing_line_item = false
964
-    ) {
965
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
966
-        $taxable_total = $total_line_item->taxable_total();
967
-
968
-        if ($add_to_existing_line_item) {
969
-            $new_tax = $tax_subtotal->get_child_line_item($code);
970
-            EEM_Line_Item::instance()->delete(
971
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
972
-            );
973
-        } else {
974
-            $new_tax = null;
975
-            $tax_subtotal->delete_children_line_items();
976
-        }
977
-        if ($new_tax) {
978
-            $new_tax->set_total($new_tax->total() + $amount);
979
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
980
-        } else {
981
-            // no existing tax item. Create it
982
-            $new_tax = EE_Line_Item::new_instance(array(
983
-                'TXN_ID' => $total_line_item->TXN_ID(),
984
-                'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
985
-                'LIN_desc' => $description ? $description : '',
986
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
987
-                'LIN_total' => $amount,
988
-                'LIN_parent' => $tax_subtotal->ID(),
989
-                'LIN_type' => EEM_Line_Item::type_tax,
990
-                'LIN_code' => $code
991
-            ));
992
-        }
993
-
994
-        $new_tax = apply_filters(
995
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
996
-            $new_tax,
997
-            $total_line_item
998
-        );
999
-        $new_tax->save();
1000
-        $tax_subtotal->set_total($new_tax->total());
1001
-        $tax_subtotal->save();
1002
-        $total_line_item->recalculate_total_including_taxes();
1003
-        return $new_tax;
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Makes all the line items which are children of $line_item taxable (or not).
1009
-     * Does NOT save the line items
1010
-     * @param EE_Line_Item $line_item
1011
-     * @param string $code_substring_for_whitelist if this string is part of the line item's code
1012
-     *  it will be whitelisted (ie, except from becoming taxable)
1013
-     * @param boolean $taxable
1014
-     */
1015
-    public static function set_line_items_taxable(
1016
-        EE_Line_Item $line_item,
1017
-        $taxable = true,
1018
-        $code_substring_for_whitelist = null
1019
-    ) {
1020
-        $whitelisted = false;
1021
-        if ($code_substring_for_whitelist !== null) {
1022
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1023
-        }
1024
-        if (!$whitelisted && $line_item->is_line_item()) {
1025
-            $line_item->set_is_taxable($taxable);
1026
-        }
1027
-        foreach ($line_item->children() as $child_line_item) {
1028
-            EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1029
-        }
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * Gets all descendants that are event subtotals
1035
-     *
1036
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1037
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1038
-     * @return EE_Line_Item[]
1039
-     */
1040
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1041
-    {
1042
-        return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1043
-    }
1044
-
1045
-
1046
-    /**
1047
-     * Gets all descendants subtotals that match the supplied object type
1048
-     *
1049
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1050
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1051
-     * @param string $obj_type
1052
-     * @return EE_Line_Item[]
1053
-     */
1054
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1055
-    {
1056
-        return self::_get_descendants_by_type_and_object_type(
1057
-            $parent_line_item,
1058
-            EEM_Line_Item::type_sub_total,
1059
-            $obj_type
1060
-        );
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * Gets all descendants that are tickets
1066
-     *
1067
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1068
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1069
-     * @return EE_Line_Item[]
1070
-     */
1071
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1072
-    {
1073
-        return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * Gets all descendants subtotals that match the supplied object type
1079
-     *
1080
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1081
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1082
-     * @param string $obj_type
1083
-     * @return EE_Line_Item[]
1084
-     */
1085
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1086
-    {
1087
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1093
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1094
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1095
-     * @return EE_Line_Item[]
1096
-     */
1097
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1098
-    {
1099
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     * Gets all the real items purchased which are children of this item
1105
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1106
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1107
-     * @return EE_Line_Item[]
1108
-     */
1109
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1110
-    {
1111
-        return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     * Gets all descendants of supplied line item that match the supplied line item type
1117
-     *
1118
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1119
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1120
-     * @param string $line_item_type one of the EEM_Line_Item constants
1121
-     * @return EE_Line_Item[]
1122
-     */
1123
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1124
-    {
1125
-        return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, null);
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1131
-     *
1132
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1133
-     * @param string $line_item_type one of the EEM_Line_Item constants
1134
-     * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1135
-     * @return EE_Line_Item[]
1136
-     */
1137
-    protected static function _get_descendants_by_type_and_object_type(
1138
-        EE_Line_Item $parent_line_item,
1139
-        $line_item_type,
1140
-        $obj_type = null
1141
-    ) {
1142
-        $objects = array();
1143
-        foreach ($parent_line_item->children() as $child_line_item) {
1144
-            if ($child_line_item instanceof EE_Line_Item) {
1145
-                if ($child_line_item->type() === $line_item_type
1146
-                    && (
1147
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1148
-                    )
1149
-                ) {
1150
-                    $objects[] = $child_line_item;
1151
-                } else {
1152
-                    // go-through-all-its children looking for more matches
1153
-                    $objects = array_merge(
1154
-                        $objects,
1155
-                        self::_get_descendants_by_type_and_object_type(
1156
-                            $child_line_item,
1157
-                            $line_item_type,
1158
-                            $obj_type
1159
-                        )
1160
-                    );
1161
-                }
1162
-            }
1163
-        }
1164
-        return $objects;
1165
-    }
1166
-
1167
-
1168
-    /**
1169
-     * Gets all descendants subtotals that match the supplied object type
1170
-     *
1171
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1172
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1173
-     * @param string $OBJ_type object type (like Event)
1174
-     * @param array $OBJ_IDs array of OBJ_IDs
1175
-     * @return EE_Line_Item[]
1176
-     */
1177
-    public static function get_line_items_by_object_type_and_IDs(
1178
-        EE_Line_Item $parent_line_item,
1179
-        $OBJ_type = '',
1180
-        $OBJ_IDs = array()
1181
-    ) {
1182
-        return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1188
-     *
1189
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1190
-     * @param string $OBJ_type object type (like Event)
1191
-     * @param array $OBJ_IDs array of OBJ_IDs
1192
-     * @return EE_Line_Item[]
1193
-     */
1194
-    protected static function _get_descendants_by_object_type_and_object_ID(
1195
-        EE_Line_Item $parent_line_item,
1196
-        $OBJ_type,
1197
-        $OBJ_IDs
1198
-    ) {
1199
-        $objects = array();
1200
-        foreach ($parent_line_item->children() as $child_line_item) {
1201
-            if ($child_line_item instanceof EE_Line_Item) {
1202
-                if ($child_line_item->OBJ_type() === $OBJ_type
1203
-                    && is_array($OBJ_IDs)
1204
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1205
-                ) {
1206
-                    $objects[] = $child_line_item;
1207
-                } else {
1208
-                    // go-through-all-its children looking for more matches
1209
-                    $objects = array_merge(
1210
-                        $objects,
1211
-                        self::_get_descendants_by_object_type_and_object_ID(
1212
-                            $child_line_item,
1213
-                            $OBJ_type,
1214
-                            $OBJ_IDs
1215
-                        )
1216
-                    );
1217
-                }
1218
-            }
1219
-        }
1220
-        return $objects;
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * Uses a breadth-first-search in order to find the nearest descendant of
1226
-     * the specified type and returns it, else NULL
1227
-     *
1228
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1229
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1230
-     * @param string $type like one of the EEM_Line_Item::type_*
1231
-     * @return EE_Line_Item
1232
-     */
1233
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1234
-    {
1235
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     * Uses a breadth-first-search in order to find the nearest descendant
1241
-     * having the specified LIN_code and returns it, else NULL
1242
-     *
1243
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1244
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1245
-     * @param string $code any value used for LIN_code
1246
-     * @return EE_Line_Item
1247
-     */
1248
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1249
-    {
1250
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * Uses a breadth-first-search in order to find the nearest descendant
1256
-     * having the specified LIN_code and returns it, else NULL
1257
-     *
1258
-     * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1259
-     * @param string $search_field name of EE_Line_Item property
1260
-     * @param string $value any value stored in $search_field
1261
-     * @return EE_Line_Item
1262
-     */
1263
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1264
-    {
1265
-        foreach ($parent_line_item->children() as $child) {
1266
-            if ($child->get($search_field) == $value) {
1267
-                return $child;
1268
-            }
1269
-        }
1270
-        foreach ($parent_line_item->children() as $child) {
1271
-            $descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1272
-            if ($descendant_found) {
1273
-                return $descendant_found;
1274
-            }
1275
-        }
1276
-        return null;
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1282
-     * else recursively walks up the line item tree until a parent of type total is found,
1283
-     *
1284
-     * @param EE_Line_Item $line_item
1285
-     * @return \EE_Line_Item
1286
-     * @throws \EE_Error
1287
-     */
1288
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1289
-    {
1290
-        if ($line_item->TXN_ID()) {
1291
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1292
-            if ($total_line_item instanceof EE_Line_Item) {
1293
-                return $total_line_item;
1294
-            }
1295
-        } else {
1296
-            $line_item_parent = $line_item->parent();
1297
-            if ($line_item_parent instanceof EE_Line_Item) {
1298
-                if ($line_item_parent->is_total()) {
1299
-                    return $line_item_parent;
1300
-                }
1301
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1302
-            }
1303
-        }
1304
-        throw new EE_Error(
1305
-            sprintf(
1306
-                __('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1307
-                $line_item->ID()
1308
-            )
1309
-        );
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * Prints out a representation of the line item tree
1315
-     *
1316
-     * @param EE_Line_Item $line_item
1317
-     * @param int $indentation
1318
-     * @return void
1319
-     * @throws \EE_Error
1320
-     */
1321
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1322
-    {
1323
-        echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1324
-        if (!$indentation) {
1325
-            echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1326
-        }
1327
-        for ($i = 0; $i < $indentation; $i++) {
1328
-            echo ". ";
1329
-        }
1330
-        $breakdown = '';
1331
-        if ($line_item->is_line_item()) {
1332
-            if ($line_item->is_percent()) {
1333
-                $breakdown = "{$line_item->percent()}%";
1334
-            } else {
1335
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1336
-            }
1337
-        }
1338
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1339
-        if ($breakdown) {
1340
-            echo " ( {$breakdown} )";
1341
-        }
1342
-        if ($line_item->is_taxable()) {
1343
-            echo "  * taxable";
1344
-        }
1345
-        if ($line_item->children()) {
1346
-            foreach ($line_item->children() as $child) {
1347
-                self::visualize($child, $indentation + 1);
1348
-            }
1349
-        }
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * Calculates the registration's final price, taking into account that they
1355
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1356
-     * and receive a portion of any transaction-wide discounts.
1357
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1358
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1359
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1360
-     * and brent's final price should be $5.50.
1361
-     *
1362
-     * In order to do this, we basically need to traverse the line item tree calculating
1363
-     * the running totals (just as if we were recalculating the total), but when we identify
1364
-     * regular line items, we need to keep track of their share of the grand total.
1365
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1366
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1367
-     * when there are non-taxable items; otherwise they would be the same)
1368
-     *
1369
-     * @param EE_Line_Item $line_item
1370
-     * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1371
-     *                                                                            can be included in price calculations at this moment
1372
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1373
-     *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1374
-     *                                          array(
1375
-     *                                          12 => 4.3
1376
-     *                                          23 => 8.0
1377
-     *                                          'total' => 16.6,
1378
-     *                                          'taxable' => array(
1379
-     *                                          12 => 10,
1380
-     *                                          23 => 4
1381
-     *                                          ).
1382
-     *                                          So to find which registrations have which final price, we need to find which line item
1383
-     *                                          is theirs, which can be done with
1384
-     *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1385
-     */
1386
-    public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1387
-    {
1388
-        // init running grand total if not already
1389
-        if (!isset($running_totals['total'])) {
1390
-            $running_totals['total'] = 0;
1391
-        }
1392
-        if (!isset($running_totals['taxable'])) {
1393
-            $running_totals['taxable'] = array('total' => 0);
1394
-        }
1395
-        foreach ($line_item->children() as $child_line_item) {
1396
-            switch ($child_line_item->type()) {
1397
-                case EEM_Line_Item::type_sub_total:
1398
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1399
-                    // combine arrays but preserve numeric keys
1400
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1401
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1402
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1403
-                    break;
1404
-
1405
-                case EEM_Line_Item::type_tax_sub_total:
1406
-                    // find how much the taxes percentage is
1407
-                    if ($child_line_item->percent() !== 0) {
1408
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1409
-                    } else {
1410
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1411
-                    }
1412
-                    // and apply to all the taxable totals, and add to the pretax totals
1413
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1414
-                        // "total" and "taxable" array key is an exception
1415
-                        if ($line_item_id === 'taxable') {
1416
-                            continue;
1417
-                        }
1418
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1419
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1420
-                    }
1421
-                    break;
1422
-
1423
-                case EEM_Line_Item::type_line_item:
1424
-                    // ticket line items or ????
1425
-                    if ($child_line_item->OBJ_type() === 'Ticket') {
1426
-                        // kk it's a ticket
1427
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1428
-                            // huh? that shouldn't happen.
1429
-                            $running_totals['total'] += $child_line_item->total();
1430
-                        } else {
1431
-                            // its not in our running totals yet. great.
1432
-                            if ($child_line_item->is_taxable()) {
1433
-                                $taxable_amount = $child_line_item->unit_price();
1434
-                            } else {
1435
-                                $taxable_amount = 0;
1436
-                            }
1437
-                            // are we only calculating totals for some tickets?
1438
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1439
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1440
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1441
-                                    ? $child_line_item->unit_price()
1442
-                                    : 0;
1443
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1444
-                                    ? $taxable_amount
1445
-                                    : 0;
1446
-                            } else {
1447
-                                $quantity = $child_line_item->quantity();
1448
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1449
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1450
-                            }
1451
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1452
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1453
-                        }
1454
-                    } else {
1455
-                        // it's some other type of item added to the cart
1456
-                        // it should affect the running totals
1457
-                        // basically we want to convert it into a PERCENT modifier. Because
1458
-                        // more clearly affect all registration's final price equally
1459
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1460
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1461
-                            : 1;
1462
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1463
-                            // the "taxable" array key is an exception
1464
-                            if ($line_item_id === 'taxable') {
1465
-                                continue;
1466
-                            }
1467
-                            // update the running totals
1468
-                            // yes this actually even works for the running grand total!
1469
-                            $running_totals[ $line_item_id ] =
1470
-                                $line_items_percent_of_running_total * $this_running_total;
1471
-
1472
-                            if ($child_line_item->is_taxable()) {
1473
-                                $running_totals['taxable'][ $line_item_id ] =
1474
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1475
-                            }
1476
-                        }
1477
-                    }
1478
-                    break;
1479
-            }
1480
-        }
1481
-        return $running_totals;
1482
-    }
1483
-
1484
-
1485
-    /**
1486
-     * @param \EE_Line_Item $total_line_item
1487
-     * @param \EE_Line_Item $ticket_line_item
1488
-     * @return float | null
1489
-     * @throws \OutOfRangeException
1490
-     */
1491
-    public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1492
-    {
1493
-        static $final_prices_per_ticket_line_item = array();
1494
-        if (empty($final_prices_per_ticket_line_item)) {
1495
-            $final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1496
-                $total_line_item
1497
-            );
1498
-        }
1499
-        // ok now find this new registration's final price
1500
-        if (isset($final_prices_per_ticket_line_item[ $ticket_line_item->ID() ])) {
1501
-            return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1502
-        }
1503
-        $message = sprintf(
1504
-            __(
1505
-                'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1506
-                'event_espresso'
1507
-            ),
1508
-            $ticket_line_item->ID()
1509
-        );
1510
-        if (WP_DEBUG) {
1511
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1512
-            throw new \OutOfRangeException($message);
1513
-        } else {
1514
-            EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1515
-        }
1516
-        return null;
1517
-    }
1518
-
1519
-
1520
-    /**
1521
-     * Creates a duplicate of the line item tree, except only includes billable items
1522
-     * and the portion of line items attributed to billable things
1523
-     *
1524
-     * @param EE_Line_Item $line_item
1525
-     * @param EE_Registration[] $registrations
1526
-     * @return \EE_Line_Item
1527
-     * @throws \EE_Error
1528
-     */
1529
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1530
-    {
1531
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1532
-        foreach ($line_item->children() as $child_li) {
1533
-            $copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1534
-        }
1535
-        // if this is the grand total line item, make sure the totals all add up
1536
-        // (we could have duplicated this logic AS we copied the line items, but
1537
-        // it seems DRYer this way)
1538
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1539
-            $copy_li->recalculate_total_including_taxes();
1540
-        }
1541
-        return $copy_li;
1542
-    }
1543
-
1544
-
1545
-    /**
1546
-     * Creates a new, unsaved line item from $line_item that factors in the
1547
-     * number of billable registrations on $registrations.
1548
-     *
1549
-     * @param EE_Line_Item $line_item
1550
-     * @return EE_Line_Item
1551
-     * @throws \EE_Error
1552
-     * @param EE_Registration[] $registrations
1553
-     */
1554
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1555
-    {
1556
-        $new_li_fields = $line_item->model_field_array();
1557
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1558
-            $line_item->OBJ_type() === 'Ticket'
1559
-        ) {
1560
-            $count = 0;
1561
-            foreach ($registrations as $registration) {
1562
-                if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1563
-                    in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1564
-                ) {
1565
-                    $count++;
1566
-                }
1567
-            }
1568
-            $new_li_fields['LIN_quantity'] = $count;
1569
-        }
1570
-        // don't set the total. We'll leave that up to the code that calculates it
1571
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1572
-        return EE_Line_Item::new_instance($new_li_fields);
1573
-    }
1574
-
1575
-
1576
-    /**
1577
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1578
-     * are removed, and line items with a quantity of 0
1579
-     *
1580
-     * @param EE_Line_Item $line_item |null
1581
-     * @return \EE_Line_Item|null
1582
-     * @throws \EE_Error
1583
-     */
1584
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1585
-    {
1586
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1587
-        if ($copied_li === null) {
1588
-            return null;
1589
-        }
1590
-        // if this is an event subtotal, we want to only include it if it
1591
-        // has a non-zero total and at least one ticket line item child
1592
-        $ticket_children = 0;
1593
-        foreach ($line_item->children() as $child_li) {
1594
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1595
-            if ($child_li_copy !== null) {
1596
-                $copied_li->add_child_line_item($child_li_copy);
1597
-                if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1598
-                    $child_li_copy->OBJ_type() === 'Ticket'
1599
-                ) {
1600
-                    $ticket_children++;
1601
-                }
1602
-            }
1603
-        }
1604
-        // if this is an event subtotal with NO ticket children
1605
-        // we basically want to ignore it
1606
-        if ($ticket_children === 0
1607
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1608
-            && $line_item->OBJ_type() === 'Event'
1609
-            && $line_item->total() === 0
1610
-        ) {
1611
-            return null;
1612
-        }
1613
-        return $copied_li;
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     * Creates a new, unsaved line item, but if it's a ticket line item
1619
-     * with a total of 0, or a subtotal of 0, returns null instead
1620
-     *
1621
-     * @param EE_Line_Item $line_item
1622
-     * @return EE_Line_Item
1623
-     * @throws \EE_Error
1624
-     */
1625
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1626
-    {
1627
-        if ($line_item->type() === EEM_Line_Item::type_line_item &&
1628
-            $line_item->OBJ_type() === 'Ticket' &&
1629
-            $line_item->quantity() === 0
1630
-        ) {
1631
-            return null;
1632
-        }
1633
-        $new_li_fields = $line_item->model_field_array();
1634
-        // don't set the total. We'll leave that up to the code that calculates it
1635
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1636
-        return EE_Line_Item::new_instance($new_li_fields);
1637
-    }
1638
-
1639
-
1640
-
1641
-    /**************************************** @DEPRECATED METHODS *************************************** */
1642
-    /**
1643
-     * @deprecated
1644
-     * @param EE_Line_Item $total_line_item
1645
-     * @return \EE_Line_Item
1646
-     * @throws \EE_Error
1647
-     */
1648
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
1649
-    {
1650
-        EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1651
-        return self::get_pre_tax_subtotal($total_line_item);
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * @deprecated
1657
-     * @param EE_Transaction $transaction
1658
-     * @return \EE_Line_Item
1659
-     * @throws \EE_Error
1660
-     */
1661
-    public static function create_default_total_line_item($transaction = null)
1662
-    {
1663
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1664
-        return self::create_total_line_item($transaction);
1665
-    }
1666
-
1667
-
1668
-    /**
1669
-     * @deprecated
1670
-     * @param EE_Line_Item $total_line_item
1671
-     * @param EE_Transaction $transaction
1672
-     * @return \EE_Line_Item
1673
-     * @throws \EE_Error
1674
-     */
1675
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1676
-    {
1677
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1678
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
1679
-    }
1680
-
1681
-
1682
-    /**
1683
-     * @deprecated
1684
-     * @param EE_Line_Item $total_line_item
1685
-     * @param EE_Transaction $transaction
1686
-     * @return \EE_Line_Item
1687
-     * @throws \EE_Error
1688
-     */
1689
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1690
-    {
1691
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1692
-        return self::create_taxes_subtotal($total_line_item, $transaction);
1693
-    }
1694
-
1695
-
1696
-    /**
1697
-     * @deprecated
1698
-     * @param EE_Line_Item $total_line_item
1699
-     * @param EE_Transaction $transaction
1700
-     * @return \EE_Line_Item
1701
-     * @throws \EE_Error
1702
-     */
1703
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1704
-    {
1705
-        EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1706
-        return self::create_event_subtotal($total_line_item, $transaction);
1707
-    }
23
+	// other functions: cancel ticket purchase
24
+	// delete ticket purchase
25
+	// add promotion
26
+
27
+
28
+	/**
29
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
30
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
31
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
32
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
33
+	 * to keep the registration final prices in-sync with the transaction's total.
34
+	 *
35
+	 * @param EE_Line_Item $parent_line_item
36
+	 * @param string $name
37
+	 * @param float $unit_price
38
+	 * @param string $description
39
+	 * @param int $quantity
40
+	 * @param boolean $taxable
41
+	 * @param boolean $code if set to a value, ensures there is only one line item with that code
42
+	 * @return boolean success
43
+	 * @throws \EE_Error
44
+	 */
45
+	public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = false, $code = null)
46
+	{
47
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
48
+		$line_item = EE_Line_Item::new_instance(array(
49
+			'LIN_name' => $name,
50
+			'LIN_desc' => $description,
51
+			'LIN_unit_price' => $unit_price,
52
+			'LIN_quantity' => $quantity,
53
+			'LIN_percent' => null,
54
+			'LIN_is_taxable' => $taxable,
55
+			'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
56
+			'LIN_total' => (float) $unit_price * (int) $quantity,
57
+			'LIN_type' => EEM_Line_Item::type_line_item,
58
+			'LIN_code' => $code,
59
+		));
60
+		$line_item = apply_filters(
61
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
62
+			$line_item,
63
+			$parent_line_item
64
+		);
65
+		return self::add_item($parent_line_item, $line_item);
66
+	}
67
+
68
+
69
+	/**
70
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
71
+	 * in the correct spot in the line item tree. Automatically
72
+	 * re-calculates the line item totals and updates the related transaction. But
73
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
74
+	 * should probably change because of this).
75
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
76
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
77
+	 *
78
+	 * @param EE_Line_Item $parent_line_item
79
+	 * @param string $name
80
+	 * @param float $percentage_amount
81
+	 * @param string $description
82
+	 * @param boolean $taxable
83
+	 * @return boolean success
84
+	 * @throws \EE_Error
85
+	 */
86
+	public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = false)
87
+	{
88
+		$line_item = EE_Line_Item::new_instance(array(
89
+			'LIN_name' => $name,
90
+			'LIN_desc' => $description,
91
+			'LIN_unit_price' => 0,
92
+			'LIN_percent' => $percentage_amount,
93
+			'LIN_quantity' => 1,
94
+			'LIN_is_taxable' => $taxable,
95
+			'LIN_total' => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
96
+			'LIN_type' => EEM_Line_Item::type_line_item,
97
+			'LIN_parent' => $parent_line_item->ID()
98
+		));
99
+		$line_item = apply_filters(
100
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
101
+			$line_item
102
+		);
103
+		return $parent_line_item->add_child_line_item($line_item, false);
104
+	}
105
+
106
+
107
+	/**
108
+	 * Returns the new line item created by adding a purchase of the ticket
109
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
110
+	 * If this ticket has already been purchased, just increments its count.
111
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
112
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
113
+	 * should probably change because of this).
114
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
115
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
116
+	 *
117
+	 * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
118
+	 * @param EE_Ticket $ticket
119
+	 * @param int $qty
120
+	 * @return \EE_Line_Item
121
+	 * @throws \EE_Error
122
+	 */
123
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
124
+	{
125
+		if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
126
+			throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
127
+		}
128
+		// either increment the qty for an existing ticket
129
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
130
+		// or add a new one
131
+		if (!$line_item instanceof EE_Line_Item) {
132
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
133
+		}
134
+		$total_line_item->recalculate_total_including_taxes();
135
+		return $line_item;
136
+	}
137
+
138
+
139
+	/**
140
+	 * Returns the new line item created by adding a purchase of the ticket
141
+	 * @param \EE_Line_Item $total_line_item
142
+	 * @param EE_Ticket $ticket
143
+	 * @param int $qty
144
+	 * @return \EE_Line_Item
145
+	 * @throws \EE_Error
146
+	 */
147
+	public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
148
+	{
149
+		$line_item = null;
150
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
151
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
152
+			foreach ((array) $ticket_line_items as $ticket_line_item) {
153
+				if ($ticket_line_item instanceof EE_Line_Item
154
+					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
155
+				) {
156
+					$line_item = $ticket_line_item;
157
+					break;
158
+				}
159
+			}
160
+		}
161
+		if ($line_item instanceof EE_Line_Item) {
162
+			EEH_Line_Item::increment_quantity($line_item, $qty);
163
+			return $line_item;
164
+		}
165
+		return null;
166
+	}
167
+
168
+
169
+	/**
170
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
171
+	 * Does NOT save or recalculate other line items totals
172
+	 *
173
+	 * @param EE_Line_Item $line_item
174
+	 * @param int $qty
175
+	 * @return void
176
+	 * @throws \EE_Error
177
+	 */
178
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
179
+	{
180
+		if (!$line_item->is_percent()) {
181
+			$qty += $line_item->quantity();
182
+			$line_item->set_quantity($qty);
183
+			$line_item->set_total($line_item->unit_price() * $qty);
184
+			$line_item->save();
185
+		}
186
+		foreach ($line_item->children() as $child) {
187
+			if ($child->is_sub_line_item()) {
188
+				EEH_Line_Item::update_quantity($child, $qty);
189
+			}
190
+		}
191
+	}
192
+
193
+
194
+	/**
195
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
196
+	 * Does NOT save or recalculate other line items totals
197
+	 *
198
+	 * @param EE_Line_Item $line_item
199
+	 * @param int $qty
200
+	 * @return void
201
+	 * @throws \EE_Error
202
+	 */
203
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
204
+	{
205
+		if (!$line_item->is_percent()) {
206
+			$qty = $line_item->quantity() - $qty;
207
+			$qty = max($qty, 0);
208
+			$line_item->set_quantity($qty);
209
+			$line_item->set_total($line_item->unit_price() * $qty);
210
+			$line_item->save();
211
+		}
212
+		foreach ($line_item->children() as $child) {
213
+			if ($child->is_sub_line_item()) {
214
+				EEH_Line_Item::update_quantity($child, $qty);
215
+			}
216
+		}
217
+	}
218
+
219
+
220
+	/**
221
+	 * Updates the line item and its children's quantities to the specified number.
222
+	 * Does NOT save them or recalculate totals.
223
+	 *
224
+	 * @param EE_Line_Item $line_item
225
+	 * @param int $new_quantity
226
+	 * @throws \EE_Error
227
+	 */
228
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
229
+	{
230
+		if (!$line_item->is_percent()) {
231
+			$line_item->set_quantity($new_quantity);
232
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
233
+			$line_item->save();
234
+		}
235
+		foreach ($line_item->children() as $child) {
236
+			if ($child->is_sub_line_item()) {
237
+				EEH_Line_Item::update_quantity($child, $new_quantity);
238
+			}
239
+		}
240
+	}
241
+
242
+
243
+	/**
244
+	 * Returns the new line item created by adding a purchase of the ticket
245
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
246
+	 * @param EE_Ticket $ticket
247
+	 * @param int $qty
248
+	 * @return \EE_Line_Item
249
+	 * @throws \EE_Error
250
+	 */
251
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
252
+	{
253
+		$datetimes = $ticket->datetimes();
254
+		$first_datetime = reset($datetimes);
255
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
256
+			$first_datetime_name = $first_datetime->event()->name();
257
+		} else {
258
+			$first_datetime_name = __('Event', 'event_espresso');
259
+		}
260
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
261
+		// get event subtotal line
262
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
263
+		// add $ticket to cart
264
+		$line_item = EE_Line_Item::new_instance(array(
265
+			'LIN_name' => $ticket->name(),
266
+			'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
267
+			'LIN_unit_price' => $ticket->price(),
268
+			'LIN_quantity' => $qty,
269
+			'LIN_is_taxable' => $ticket->taxable(),
270
+			'LIN_order' => count($events_sub_total->children()),
271
+			'LIN_total' => $ticket->price() * $qty,
272
+			'LIN_type' => EEM_Line_Item::type_line_item,
273
+			'OBJ_ID' => $ticket->ID(),
274
+			'OBJ_type' => 'Ticket'
275
+		));
276
+		$line_item = apply_filters(
277
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
278
+			$line_item
279
+		);
280
+		$events_sub_total->add_child_line_item($line_item);
281
+		// now add the sub-line items
282
+		$running_total_for_ticket = 0;
283
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
284
+			$sign = $price->is_discount() ? -1 : 1;
285
+			$price_total = $price->is_percent()
286
+				? $running_total_for_ticket * $price->amount() / 100
287
+				: $price->amount() * $qty;
288
+			$sub_line_item = EE_Line_Item::new_instance(array(
289
+				'LIN_name' => $price->name(),
290
+				'LIN_desc' => $price->desc(),
291
+				'LIN_quantity' => $price->is_percent() ? null : $qty,
292
+				'LIN_is_taxable' => false,
293
+				'LIN_order' => $price->order(),
294
+				'LIN_total' => $sign * $price_total,
295
+				'LIN_type' => EEM_Line_Item::type_sub_line_item,
296
+				'OBJ_ID' => $price->ID(),
297
+				'OBJ_type' => 'Price'
298
+			));
299
+			$sub_line_item = apply_filters(
300
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
301
+				$sub_line_item
302
+			);
303
+			if ($price->is_percent()) {
304
+				$sub_line_item->set_percent($sign * $price->amount());
305
+			} else {
306
+				$sub_line_item->set_unit_price($sign * $price->amount());
307
+			}
308
+			$running_total_for_ticket += $price_total;
309
+			$line_item->add_child_line_item($sub_line_item);
310
+		}
311
+		return $line_item;
312
+	}
313
+
314
+
315
+	/**
316
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
317
+	 * re-calculates the line item totals and updates the related transaction. But
318
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
319
+	 * should probably change because of this).
320
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
321
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
322
+	 *
323
+	 * @param EE_Line_Item $total_line_item
324
+	 * @param EE_Line_Item $item to be added
325
+	 * @return boolean
326
+	 * @throws \EE_Error
327
+	 */
328
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
329
+	{
330
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
331
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
332
+			$success = $pre_tax_subtotal->add_child_line_item($item);
333
+		} else {
334
+			return false;
335
+		}
336
+		$total_line_item->recalculate_total_including_taxes();
337
+		return $success;
338
+	}
339
+
340
+
341
+	/**
342
+	 * cancels an existing ticket line item,
343
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
344
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
345
+	 *
346
+	 * @param EE_Line_Item $ticket_line_item
347
+	 * @param int $qty
348
+	 * @return bool success
349
+	 * @throws \EE_Error
350
+	 */
351
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
352
+	{
353
+		// validate incoming line_item
354
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
355
+			throw new EE_Error(
356
+				sprintf(
357
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
358
+					$ticket_line_item->type()
359
+				)
360
+			);
361
+		}
362
+		if ($ticket_line_item->quantity() < $qty) {
363
+			throw new EE_Error(
364
+				sprintf(
365
+					__('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
366
+					$qty,
367
+					$ticket_line_item->quantity()
368
+				)
369
+			);
370
+		}
371
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
372
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
373
+		foreach ($ticket_line_item->children() as $child_line_item) {
374
+			if ($child_line_item->is_sub_line_item()
375
+				&& !$child_line_item->is_percent()
376
+				&& !$child_line_item->is_cancellation()
377
+			) {
378
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
379
+			}
380
+		}
381
+		// get cancellation sub line item
382
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
383
+			$ticket_line_item,
384
+			EEM_Line_Item::type_cancellation
385
+		);
386
+		$cancellation_line_item = reset($cancellation_line_item);
387
+		// verify that this ticket was indeed previously cancelled
388
+		if ($cancellation_line_item instanceof EE_Line_Item) {
389
+			// increment cancelled quantity
390
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
391
+		} else {
392
+			// create cancellation sub line item
393
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
394
+				'LIN_name' => __('Cancellation', 'event_espresso'),
395
+				'LIN_desc' => sprintf(
396
+					_x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
397
+					$ticket_line_item->name(),
398
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
399
+				),
400
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
401
+				'LIN_quantity' => $qty,
402
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
403
+				'LIN_order' => count($ticket_line_item->children()),
404
+				'LIN_total' => 0, // $ticket_line_item->unit_price()
405
+				'LIN_type' => EEM_Line_Item::type_cancellation,
406
+			));
407
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
408
+		}
409
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
410
+			// decrement parent line item quantity
411
+			$event_line_item = $ticket_line_item->parent();
412
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
413
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
414
+				$event_line_item->save();
415
+			}
416
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
417
+			return true;
418
+		}
419
+		return false;
420
+	}
421
+
422
+
423
+	/**
424
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
425
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
426
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
427
+	 *
428
+	 * @param EE_Line_Item $ticket_line_item
429
+	 * @param int $qty
430
+	 * @return bool success
431
+	 * @throws \EE_Error
432
+	 */
433
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
434
+	{
435
+		// validate incoming line_item
436
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
437
+			throw new EE_Error(
438
+				sprintf(
439
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
440
+					$ticket_line_item->type()
441
+				)
442
+			);
443
+		}
444
+		// get cancellation sub line item
445
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
446
+			$ticket_line_item,
447
+			EEM_Line_Item::type_cancellation
448
+		);
449
+		$cancellation_line_item = reset($cancellation_line_item);
450
+		// verify that this ticket was indeed previously cancelled
451
+		if (!$cancellation_line_item instanceof EE_Line_Item) {
452
+			return false;
453
+		}
454
+		if ($cancellation_line_item->quantity() > $qty) {
455
+			// decrement cancelled quantity
456
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
457
+		} elseif ($cancellation_line_item->quantity() == $qty) {
458
+			// decrement cancelled quantity in case anyone still has the object kicking around
459
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
460
+			// delete because quantity will end up as 0
461
+			$cancellation_line_item->delete();
462
+			// and attempt to destroy the object,
463
+			// even though PHP won't actually destroy it until it needs the memory
464
+			unset($cancellation_line_item);
465
+		} else {
466
+			// what ?!?! negative quantity ?!?!
467
+			throw new EE_Error(
468
+				sprintf(
469
+					__(
470
+						'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
471
+						'event_espresso'
472
+					),
473
+					$qty,
474
+					$cancellation_line_item->quantity()
475
+				)
476
+			);
477
+		}
478
+		// increment ticket quantity
479
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
480
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
481
+			// increment parent line item quantity
482
+			$event_line_item = $ticket_line_item->parent();
483
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
484
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
485
+			}
486
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
487
+			return true;
488
+		}
489
+		return false;
490
+	}
491
+
492
+
493
+	/**
494
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
495
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
496
+	 *
497
+	 * @param EE_Line_Item $line_item
498
+	 * @return \EE_Line_Item
499
+	 */
500
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
501
+	{
502
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
503
+		return $grand_total_line_item->recalculate_total_including_taxes();
504
+	}
505
+
506
+
507
+	/**
508
+	 * Gets the line item which contains the subtotal of all the items
509
+	 *
510
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
511
+	 * @return \EE_Line_Item
512
+	 * @throws \EE_Error
513
+	 */
514
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
515
+	{
516
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
517
+		return $pre_tax_subtotal instanceof EE_Line_Item
518
+			? $pre_tax_subtotal
519
+			: self::create_pre_tax_subtotal($total_line_item);
520
+	}
521
+
522
+
523
+	/**
524
+	 * Gets the line item for the taxes subtotal
525
+	 *
526
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
527
+	 * @return \EE_Line_Item
528
+	 * @throws \EE_Error
529
+	 */
530
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
531
+	{
532
+		$taxes = $total_line_item->get_child_line_item('taxes');
533
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
534
+	}
535
+
536
+
537
+	/**
538
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
539
+	 *
540
+	 * @param EE_Line_Item $line_item
541
+	 * @param EE_Transaction $transaction
542
+	 * @return void
543
+	 * @throws \EE_Error
544
+	 */
545
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
546
+	{
547
+		if ($transaction) {
548
+			/** @type EEM_Transaction $EEM_Transaction */
549
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
550
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
551
+			$line_item->set_TXN_ID($TXN_ID);
552
+		}
553
+	}
554
+
555
+
556
+	/**
557
+	 * Creates a new default total line item for the transaction,
558
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
559
+	 * existing taxes as children of the taxes subtotal line item)
560
+	 *
561
+	 * @param EE_Transaction $transaction
562
+	 * @return \EE_Line_Item of type total
563
+	 * @throws \EE_Error
564
+	 */
565
+	public static function create_total_line_item($transaction = null)
566
+	{
567
+		$total_line_item = EE_Line_Item::new_instance(array(
568
+			'LIN_code' => 'total',
569
+			'LIN_name' => __('Grand Total', 'event_espresso'),
570
+			'LIN_type' => EEM_Line_Item::type_total,
571
+			'OBJ_type' => 'Transaction'
572
+		));
573
+		$total_line_item = apply_filters(
574
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
575
+			$total_line_item
576
+		);
577
+		self::set_TXN_ID($total_line_item, $transaction);
578
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
579
+		self::create_taxes_subtotal($total_line_item, $transaction);
580
+		return $total_line_item;
581
+	}
582
+
583
+
584
+	/**
585
+	 * Creates a default items subtotal line item
586
+	 *
587
+	 * @param EE_Line_Item $total_line_item
588
+	 * @param EE_Transaction $transaction
589
+	 * @return EE_Line_Item
590
+	 * @throws \EE_Error
591
+	 */
592
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
593
+	{
594
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
595
+			'LIN_code' => 'pre-tax-subtotal',
596
+			'LIN_name' => __('Pre-Tax Subtotal', 'event_espresso'),
597
+			'LIN_type' => EEM_Line_Item::type_sub_total
598
+		));
599
+		$pre_tax_line_item = apply_filters(
600
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
601
+			$pre_tax_line_item
602
+		);
603
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
604
+		$total_line_item->add_child_line_item($pre_tax_line_item);
605
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
606
+		return $pre_tax_line_item;
607
+	}
608
+
609
+
610
+	/**
611
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
612
+	 * and applies taxes to it
613
+	 *
614
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
615
+	 * @param EE_Transaction $transaction
616
+	 * @return EE_Line_Item
617
+	 * @throws \EE_Error
618
+	 */
619
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
620
+	{
621
+		$tax_line_item = EE_Line_Item::new_instance(array(
622
+			'LIN_code' => 'taxes',
623
+			'LIN_name' => __('Taxes', 'event_espresso'),
624
+			'LIN_type' => EEM_Line_Item::type_tax_sub_total,
625
+			'LIN_order' => 1000,// this should always come last
626
+		));
627
+		$tax_line_item = apply_filters(
628
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
629
+			$tax_line_item
630
+		);
631
+		self::set_TXN_ID($tax_line_item, $transaction);
632
+		$total_line_item->add_child_line_item($tax_line_item);
633
+		// and lastly, add the actual taxes
634
+		self::apply_taxes($total_line_item);
635
+		return $tax_line_item;
636
+	}
637
+
638
+
639
+	/**
640
+	 * Creates a default items subtotal line item
641
+	 *
642
+	 * @param EE_Line_Item $pre_tax_line_item
643
+	 * @param EE_Transaction $transaction
644
+	 * @param EE_Event $event
645
+	 * @return EE_Line_Item
646
+	 * @throws \EE_Error
647
+	 */
648
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
649
+	{
650
+		$event_line_item = EE_Line_Item::new_instance(array(
651
+			'LIN_code' => self::get_event_code($event),
652
+			'LIN_name' => self::get_event_name($event),
653
+			'LIN_desc' => self::get_event_desc($event),
654
+			'LIN_type' => EEM_Line_Item::type_sub_total,
655
+			'OBJ_type' => 'Event',
656
+			'OBJ_ID' => $event instanceof EE_Event ? $event->ID() : 0
657
+		));
658
+		$event_line_item = apply_filters(
659
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
660
+			$event_line_item
661
+		);
662
+		self::set_TXN_ID($event_line_item, $transaction);
663
+		$pre_tax_line_item->add_child_line_item($event_line_item);
664
+		return $event_line_item;
665
+	}
666
+
667
+
668
+	/**
669
+	 * Gets what the event ticket's code SHOULD be
670
+	 *
671
+	 * @param EE_Event $event
672
+	 * @return string
673
+	 * @throws \EE_Error
674
+	 */
675
+	public static function get_event_code($event)
676
+	{
677
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
678
+	}
679
+
680
+	/**
681
+	 * Gets the event name
682
+	 * @param EE_Event $event
683
+	 * @return string
684
+	 */
685
+	public static function get_event_name($event)
686
+	{
687
+		return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
688
+	}
689
+
690
+	/**
691
+	 * Gets the event excerpt
692
+	 * @param EE_Event $event
693
+	 * @return string
694
+	 */
695
+	public static function get_event_desc($event)
696
+	{
697
+		return $event instanceof EE_Event ? $event->short_description() : '';
698
+	}
699
+
700
+	/**
701
+	 * Given the grand total line item and a ticket, finds the event sub-total
702
+	 * line item the ticket's purchase should be added onto
703
+	 *
704
+	 * @access public
705
+	 * @param EE_Line_Item $grand_total the grand total line item
706
+	 * @param EE_Ticket $ticket
707
+	 * @throws \EE_Error
708
+	 * @return EE_Line_Item
709
+	 */
710
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
711
+	{
712
+		$first_datetime = $ticket->first_datetime();
713
+		if (!$first_datetime instanceof EE_Datetime) {
714
+			throw new EE_Error(
715
+				sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
716
+			);
717
+		}
718
+		$event = $first_datetime->event();
719
+		if (!$event instanceof EE_Event) {
720
+			throw new EE_Error(
721
+				sprintf(
722
+					__('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
723
+					$ticket->ID()
724
+				)
725
+			);
726
+		}
727
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
728
+		if (!$events_sub_total instanceof EE_Line_Item) {
729
+			throw new EE_Error(
730
+				sprintf(
731
+					__('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
732
+					$ticket->ID(),
733
+					$grand_total->ID()
734
+				)
735
+			);
736
+		}
737
+		return $events_sub_total;
738
+	}
739
+
740
+
741
+	/**
742
+	 * Gets the event line item
743
+	 *
744
+	 * @param EE_Line_Item $grand_total
745
+	 * @param EE_Event $event
746
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
747
+	 * @throws \EE_Error
748
+	 */
749
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
750
+	{
751
+		/** @type EE_Event $event */
752
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
753
+		$event_line_item = null;
754
+		$found = false;
755
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
756
+			// default event subtotal, we should only ever find this the first time this method is called
757
+			if (!$event_line_item->OBJ_ID()) {
758
+				// let's use this! but first... set the event details
759
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
760
+				$found = true;
761
+				break;
762
+			} elseif ($event_line_item->OBJ_ID() === $event->ID()) {
763
+				// found existing line item for this event in the cart, so break out of loop and use this one
764
+				$found = true;
765
+				break;
766
+			}
767
+		}
768
+		if (!$found) {
769
+			// there is no event sub-total yet, so add it
770
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
771
+			// create a new "event" subtotal below that
772
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
773
+			// and set the event details
774
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
775
+		}
776
+		return $event_line_item;
777
+	}
778
+
779
+
780
+	/**
781
+	 * Creates a default items subtotal line item
782
+	 *
783
+	 * @param EE_Line_Item $event_line_item
784
+	 * @param EE_Event $event
785
+	 * @param EE_Transaction $transaction
786
+	 * @return EE_Line_Item
787
+	 * @throws \EE_Error
788
+	 */
789
+	public static function set_event_subtotal_details(
790
+		EE_Line_Item $event_line_item,
791
+		EE_Event $event,
792
+		$transaction = null
793
+	) {
794
+		if ($event instanceof EE_Event) {
795
+			$event_line_item->set_code(self::get_event_code($event));
796
+			$event_line_item->set_name(self::get_event_name($event));
797
+			$event_line_item->set_desc(self::get_event_desc($event));
798
+			$event_line_item->set_OBJ_ID($event->ID());
799
+		}
800
+		self::set_TXN_ID($event_line_item, $transaction);
801
+	}
802
+
803
+
804
+	/**
805
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
806
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
807
+	 * any old taxes are removed
808
+	 *
809
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
810
+	 * @throws \EE_Error
811
+	 */
812
+	public static function apply_taxes(EE_Line_Item $total_line_item)
813
+	{
814
+		/** @type EEM_Price $EEM_Price */
815
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
816
+		// get array of taxes via Price Model
817
+		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
818
+		ksort($ordered_taxes);
819
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
820
+		// just to be safe, remove its old tax line items
821
+		$taxes_line_item->delete_children_line_items();
822
+		// loop thru taxes
823
+		foreach ($ordered_taxes as $order => $taxes) {
824
+			foreach ($taxes as $tax) {
825
+				if ($tax instanceof EE_Price) {
826
+					$tax_line_item = EE_Line_Item::new_instance(
827
+						array(
828
+							'LIN_name' => $tax->name(),
829
+							'LIN_desc' => $tax->desc(),
830
+							'LIN_percent' => $tax->amount(),
831
+							'LIN_is_taxable' => false,
832
+							'LIN_order' => $order,
833
+							'LIN_total' => 0,
834
+							'LIN_type' => EEM_Line_Item::type_tax,
835
+							'OBJ_type' => 'Price',
836
+							'OBJ_ID' => $tax->ID()
837
+						)
838
+					);
839
+					$tax_line_item = apply_filters(
840
+						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
841
+						$tax_line_item
842
+					);
843
+					$taxes_line_item->add_child_line_item($tax_line_item);
844
+				}
845
+			}
846
+		}
847
+		$total_line_item->recalculate_total_including_taxes();
848
+	}
849
+
850
+
851
+	/**
852
+	 * Ensures that taxes have been applied to the order, if not applies them.
853
+	 * Returns the total amount of tax
854
+	 *
855
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
856
+	 * @return float
857
+	 * @throws \EE_Error
858
+	 */
859
+	public static function ensure_taxes_applied($total_line_item)
860
+	{
861
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
862
+		if (!$taxes_subtotal->children()) {
863
+			self::apply_taxes($total_line_item);
864
+		}
865
+		return $taxes_subtotal->total();
866
+	}
867
+
868
+
869
+	/**
870
+	 * Deletes ALL children of the passed line item
871
+	 *
872
+	 * @param EE_Line_Item $parent_line_item
873
+	 * @return bool
874
+	 * @throws \EE_Error
875
+	 */
876
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
877
+	{
878
+		$deleted = 0;
879
+		foreach ($parent_line_item->children() as $child_line_item) {
880
+			if ($child_line_item instanceof EE_Line_Item) {
881
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
882
+				if ($child_line_item->ID()) {
883
+					$child_line_item->delete();
884
+					unset($child_line_item);
885
+				} else {
886
+					$parent_line_item->delete_child_line_item($child_line_item->code());
887
+				}
888
+				$deleted++;
889
+			}
890
+		}
891
+		return $deleted;
892
+	}
893
+
894
+
895
+	/**
896
+	 * Deletes the line items as indicated by the line item code(s) provided,
897
+	 * regardless of where they're found in the line item tree. Automatically
898
+	 * re-calculates the line item totals and updates the related transaction. But
899
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
900
+	 * should probably change because of this).
901
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
902
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
903
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
904
+	 * @param array|bool|string $line_item_codes
905
+	 * @return int number of items successfully removed
906
+	 */
907
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
908
+	{
909
+
910
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
911
+			EE_Error::doing_it_wrong(
912
+				'EEH_Line_Item::delete_items',
913
+				__(
914
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
915
+					'event_espresso'
916
+				),
917
+				'4.6.18'
918
+			);
919
+		}
920
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
921
+
922
+		// check if only a single line_item_id was passed
923
+		if (!empty($line_item_codes) && !is_array($line_item_codes)) {
924
+			// place single line_item_id in an array to appear as multiple line_item_ids
925
+			$line_item_codes = array($line_item_codes);
926
+		}
927
+		$removals = 0;
928
+		// cycle thru line_item_ids
929
+		foreach ($line_item_codes as $line_item_id) {
930
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
931
+		}
932
+
933
+		if ($removals > 0) {
934
+			$total_line_item->recalculate_taxes_and_tax_total();
935
+			return $removals;
936
+		} else {
937
+			return false;
938
+		}
939
+	}
940
+
941
+
942
+	/**
943
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
944
+	 * tax and updates the total line item accordingly
945
+	 *
946
+	 * @param EE_Line_Item $total_line_item
947
+	 * @param float $amount
948
+	 * @param string $name
949
+	 * @param string $description
950
+	 * @param string $code
951
+	 * @param boolean $add_to_existing_line_item
952
+	 *                          if true, and a duplicate line item with the same code is found,
953
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
954
+	 * @return EE_Line_Item the new tax line item created
955
+	 * @throws \EE_Error
956
+	 */
957
+	public static function set_total_tax_to(
958
+		EE_Line_Item $total_line_item,
959
+		$amount,
960
+		$name = null,
961
+		$description = null,
962
+		$code = null,
963
+		$add_to_existing_line_item = false
964
+	) {
965
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
966
+		$taxable_total = $total_line_item->taxable_total();
967
+
968
+		if ($add_to_existing_line_item) {
969
+			$new_tax = $tax_subtotal->get_child_line_item($code);
970
+			EEM_Line_Item::instance()->delete(
971
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
972
+			);
973
+		} else {
974
+			$new_tax = null;
975
+			$tax_subtotal->delete_children_line_items();
976
+		}
977
+		if ($new_tax) {
978
+			$new_tax->set_total($new_tax->total() + $amount);
979
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
980
+		} else {
981
+			// no existing tax item. Create it
982
+			$new_tax = EE_Line_Item::new_instance(array(
983
+				'TXN_ID' => $total_line_item->TXN_ID(),
984
+				'LIN_name' => $name ? $name : __('Tax', 'event_espresso'),
985
+				'LIN_desc' => $description ? $description : '',
986
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
987
+				'LIN_total' => $amount,
988
+				'LIN_parent' => $tax_subtotal->ID(),
989
+				'LIN_type' => EEM_Line_Item::type_tax,
990
+				'LIN_code' => $code
991
+			));
992
+		}
993
+
994
+		$new_tax = apply_filters(
995
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
996
+			$new_tax,
997
+			$total_line_item
998
+		);
999
+		$new_tax->save();
1000
+		$tax_subtotal->set_total($new_tax->total());
1001
+		$tax_subtotal->save();
1002
+		$total_line_item->recalculate_total_including_taxes();
1003
+		return $new_tax;
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Makes all the line items which are children of $line_item taxable (or not).
1009
+	 * Does NOT save the line items
1010
+	 * @param EE_Line_Item $line_item
1011
+	 * @param string $code_substring_for_whitelist if this string is part of the line item's code
1012
+	 *  it will be whitelisted (ie, except from becoming taxable)
1013
+	 * @param boolean $taxable
1014
+	 */
1015
+	public static function set_line_items_taxable(
1016
+		EE_Line_Item $line_item,
1017
+		$taxable = true,
1018
+		$code_substring_for_whitelist = null
1019
+	) {
1020
+		$whitelisted = false;
1021
+		if ($code_substring_for_whitelist !== null) {
1022
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1023
+		}
1024
+		if (!$whitelisted && $line_item->is_line_item()) {
1025
+			$line_item->set_is_taxable($taxable);
1026
+		}
1027
+		foreach ($line_item->children() as $child_line_item) {
1028
+			EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1029
+		}
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * Gets all descendants that are event subtotals
1035
+	 *
1036
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1037
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1038
+	 * @return EE_Line_Item[]
1039
+	 */
1040
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1041
+	{
1042
+		return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1043
+	}
1044
+
1045
+
1046
+	/**
1047
+	 * Gets all descendants subtotals that match the supplied object type
1048
+	 *
1049
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1050
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1051
+	 * @param string $obj_type
1052
+	 * @return EE_Line_Item[]
1053
+	 */
1054
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1055
+	{
1056
+		return self::_get_descendants_by_type_and_object_type(
1057
+			$parent_line_item,
1058
+			EEM_Line_Item::type_sub_total,
1059
+			$obj_type
1060
+		);
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * Gets all descendants that are tickets
1066
+	 *
1067
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1068
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1069
+	 * @return EE_Line_Item[]
1070
+	 */
1071
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1072
+	{
1073
+		return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * Gets all descendants subtotals that match the supplied object type
1079
+	 *
1080
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1081
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1082
+	 * @param string $obj_type
1083
+	 * @return EE_Line_Item[]
1084
+	 */
1085
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1086
+	{
1087
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1093
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1094
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1095
+	 * @return EE_Line_Item[]
1096
+	 */
1097
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1098
+	{
1099
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 * Gets all the real items purchased which are children of this item
1105
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1106
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1107
+	 * @return EE_Line_Item[]
1108
+	 */
1109
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1110
+	{
1111
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 * Gets all descendants of supplied line item that match the supplied line item type
1117
+	 *
1118
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1119
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1120
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1121
+	 * @return EE_Line_Item[]
1122
+	 */
1123
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1124
+	{
1125
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, null);
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1131
+	 *
1132
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1133
+	 * @param string $line_item_type one of the EEM_Line_Item constants
1134
+	 * @param string | NULL $obj_type object model class name (minus prefix) or NULL to ignore object type when searching
1135
+	 * @return EE_Line_Item[]
1136
+	 */
1137
+	protected static function _get_descendants_by_type_and_object_type(
1138
+		EE_Line_Item $parent_line_item,
1139
+		$line_item_type,
1140
+		$obj_type = null
1141
+	) {
1142
+		$objects = array();
1143
+		foreach ($parent_line_item->children() as $child_line_item) {
1144
+			if ($child_line_item instanceof EE_Line_Item) {
1145
+				if ($child_line_item->type() === $line_item_type
1146
+					&& (
1147
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1148
+					)
1149
+				) {
1150
+					$objects[] = $child_line_item;
1151
+				} else {
1152
+					// go-through-all-its children looking for more matches
1153
+					$objects = array_merge(
1154
+						$objects,
1155
+						self::_get_descendants_by_type_and_object_type(
1156
+							$child_line_item,
1157
+							$line_item_type,
1158
+							$obj_type
1159
+						)
1160
+					);
1161
+				}
1162
+			}
1163
+		}
1164
+		return $objects;
1165
+	}
1166
+
1167
+
1168
+	/**
1169
+	 * Gets all descendants subtotals that match the supplied object type
1170
+	 *
1171
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1172
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1173
+	 * @param string $OBJ_type object type (like Event)
1174
+	 * @param array $OBJ_IDs array of OBJ_IDs
1175
+	 * @return EE_Line_Item[]
1176
+	 */
1177
+	public static function get_line_items_by_object_type_and_IDs(
1178
+		EE_Line_Item $parent_line_item,
1179
+		$OBJ_type = '',
1180
+		$OBJ_IDs = array()
1181
+	) {
1182
+		return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type as well
1188
+	 *
1189
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1190
+	 * @param string $OBJ_type object type (like Event)
1191
+	 * @param array $OBJ_IDs array of OBJ_IDs
1192
+	 * @return EE_Line_Item[]
1193
+	 */
1194
+	protected static function _get_descendants_by_object_type_and_object_ID(
1195
+		EE_Line_Item $parent_line_item,
1196
+		$OBJ_type,
1197
+		$OBJ_IDs
1198
+	) {
1199
+		$objects = array();
1200
+		foreach ($parent_line_item->children() as $child_line_item) {
1201
+			if ($child_line_item instanceof EE_Line_Item) {
1202
+				if ($child_line_item->OBJ_type() === $OBJ_type
1203
+					&& is_array($OBJ_IDs)
1204
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1205
+				) {
1206
+					$objects[] = $child_line_item;
1207
+				} else {
1208
+					// go-through-all-its children looking for more matches
1209
+					$objects = array_merge(
1210
+						$objects,
1211
+						self::_get_descendants_by_object_type_and_object_ID(
1212
+							$child_line_item,
1213
+							$OBJ_type,
1214
+							$OBJ_IDs
1215
+						)
1216
+					);
1217
+				}
1218
+			}
1219
+		}
1220
+		return $objects;
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1226
+	 * the specified type and returns it, else NULL
1227
+	 *
1228
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1229
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1230
+	 * @param string $type like one of the EEM_Line_Item::type_*
1231
+	 * @return EE_Line_Item
1232
+	 */
1233
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1234
+	{
1235
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 * Uses a breadth-first-search in order to find the nearest descendant
1241
+	 * having the specified LIN_code and returns it, else NULL
1242
+	 *
1243
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1244
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1245
+	 * @param string $code any value used for LIN_code
1246
+	 * @return EE_Line_Item
1247
+	 */
1248
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1249
+	{
1250
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * Uses a breadth-first-search in order to find the nearest descendant
1256
+	 * having the specified LIN_code and returns it, else NULL
1257
+	 *
1258
+	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1259
+	 * @param string $search_field name of EE_Line_Item property
1260
+	 * @param string $value any value stored in $search_field
1261
+	 * @return EE_Line_Item
1262
+	 */
1263
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1264
+	{
1265
+		foreach ($parent_line_item->children() as $child) {
1266
+			if ($child->get($search_field) == $value) {
1267
+				return $child;
1268
+			}
1269
+		}
1270
+		foreach ($parent_line_item->children() as $child) {
1271
+			$descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1272
+			if ($descendant_found) {
1273
+				return $descendant_found;
1274
+			}
1275
+		}
1276
+		return null;
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1282
+	 * else recursively walks up the line item tree until a parent of type total is found,
1283
+	 *
1284
+	 * @param EE_Line_Item $line_item
1285
+	 * @return \EE_Line_Item
1286
+	 * @throws \EE_Error
1287
+	 */
1288
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1289
+	{
1290
+		if ($line_item->TXN_ID()) {
1291
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1292
+			if ($total_line_item instanceof EE_Line_Item) {
1293
+				return $total_line_item;
1294
+			}
1295
+		} else {
1296
+			$line_item_parent = $line_item->parent();
1297
+			if ($line_item_parent instanceof EE_Line_Item) {
1298
+				if ($line_item_parent->is_total()) {
1299
+					return $line_item_parent;
1300
+				}
1301
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1302
+			}
1303
+		}
1304
+		throw new EE_Error(
1305
+			sprintf(
1306
+				__('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1307
+				$line_item->ID()
1308
+			)
1309
+		);
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * Prints out a representation of the line item tree
1315
+	 *
1316
+	 * @param EE_Line_Item $line_item
1317
+	 * @param int $indentation
1318
+	 * @return void
1319
+	 * @throws \EE_Error
1320
+	 */
1321
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1322
+	{
1323
+		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1324
+		if (!$indentation) {
1325
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1326
+		}
1327
+		for ($i = 0; $i < $indentation; $i++) {
1328
+			echo ". ";
1329
+		}
1330
+		$breakdown = '';
1331
+		if ($line_item->is_line_item()) {
1332
+			if ($line_item->is_percent()) {
1333
+				$breakdown = "{$line_item->percent()}%";
1334
+			} else {
1335
+				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1336
+			}
1337
+		}
1338
+		echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1339
+		if ($breakdown) {
1340
+			echo " ( {$breakdown} )";
1341
+		}
1342
+		if ($line_item->is_taxable()) {
1343
+			echo "  * taxable";
1344
+		}
1345
+		if ($line_item->children()) {
1346
+			foreach ($line_item->children() as $child) {
1347
+				self::visualize($child, $indentation + 1);
1348
+			}
1349
+		}
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * Calculates the registration's final price, taking into account that they
1355
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1356
+	 * and receive a portion of any transaction-wide discounts.
1357
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1358
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1359
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1360
+	 * and brent's final price should be $5.50.
1361
+	 *
1362
+	 * In order to do this, we basically need to traverse the line item tree calculating
1363
+	 * the running totals (just as if we were recalculating the total), but when we identify
1364
+	 * regular line items, we need to keep track of their share of the grand total.
1365
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1366
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1367
+	 * when there are non-taxable items; otherwise they would be the same)
1368
+	 *
1369
+	 * @param EE_Line_Item $line_item
1370
+	 * @param array $billable_ticket_quantities array of EE_Ticket IDs and their corresponding quantity that
1371
+	 *                                                                            can be included in price calculations at this moment
1372
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1373
+	 *                                          plus the key 'total', and 'taxable' which also has keys of all the ticket IDs. Eg
1374
+	 *                                          array(
1375
+	 *                                          12 => 4.3
1376
+	 *                                          23 => 8.0
1377
+	 *                                          'total' => 16.6,
1378
+	 *                                          'taxable' => array(
1379
+	 *                                          12 => 10,
1380
+	 *                                          23 => 4
1381
+	 *                                          ).
1382
+	 *                                          So to find which registrations have which final price, we need to find which line item
1383
+	 *                                          is theirs, which can be done with
1384
+	 *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1385
+	 */
1386
+	public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1387
+	{
1388
+		// init running grand total if not already
1389
+		if (!isset($running_totals['total'])) {
1390
+			$running_totals['total'] = 0;
1391
+		}
1392
+		if (!isset($running_totals['taxable'])) {
1393
+			$running_totals['taxable'] = array('total' => 0);
1394
+		}
1395
+		foreach ($line_item->children() as $child_line_item) {
1396
+			switch ($child_line_item->type()) {
1397
+				case EEM_Line_Item::type_sub_total:
1398
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1399
+					// combine arrays but preserve numeric keys
1400
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1401
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1402
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1403
+					break;
1404
+
1405
+				case EEM_Line_Item::type_tax_sub_total:
1406
+					// find how much the taxes percentage is
1407
+					if ($child_line_item->percent() !== 0) {
1408
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1409
+					} else {
1410
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1411
+					}
1412
+					// and apply to all the taxable totals, and add to the pretax totals
1413
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1414
+						// "total" and "taxable" array key is an exception
1415
+						if ($line_item_id === 'taxable') {
1416
+							continue;
1417
+						}
1418
+						$taxable_total = $running_totals['taxable'][ $line_item_id ];
1419
+						$running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1420
+					}
1421
+					break;
1422
+
1423
+				case EEM_Line_Item::type_line_item:
1424
+					// ticket line items or ????
1425
+					if ($child_line_item->OBJ_type() === 'Ticket') {
1426
+						// kk it's a ticket
1427
+						if (isset($running_totals[ $child_line_item->ID() ])) {
1428
+							// huh? that shouldn't happen.
1429
+							$running_totals['total'] += $child_line_item->total();
1430
+						} else {
1431
+							// its not in our running totals yet. great.
1432
+							if ($child_line_item->is_taxable()) {
1433
+								$taxable_amount = $child_line_item->unit_price();
1434
+							} else {
1435
+								$taxable_amount = 0;
1436
+							}
1437
+							// are we only calculating totals for some tickets?
1438
+							if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1439
+								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1440
+								$running_totals[ $child_line_item->ID() ] = $quantity
1441
+									? $child_line_item->unit_price()
1442
+									: 0;
1443
+								$running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1444
+									? $taxable_amount
1445
+									: 0;
1446
+							} else {
1447
+								$quantity = $child_line_item->quantity();
1448
+								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1449
+								$running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1450
+							}
1451
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1452
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1453
+						}
1454
+					} else {
1455
+						// it's some other type of item added to the cart
1456
+						// it should affect the running totals
1457
+						// basically we want to convert it into a PERCENT modifier. Because
1458
+						// more clearly affect all registration's final price equally
1459
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1460
+							? ($child_line_item->total() / $running_totals['total']) + 1
1461
+							: 1;
1462
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1463
+							// the "taxable" array key is an exception
1464
+							if ($line_item_id === 'taxable') {
1465
+								continue;
1466
+							}
1467
+							// update the running totals
1468
+							// yes this actually even works for the running grand total!
1469
+							$running_totals[ $line_item_id ] =
1470
+								$line_items_percent_of_running_total * $this_running_total;
1471
+
1472
+							if ($child_line_item->is_taxable()) {
1473
+								$running_totals['taxable'][ $line_item_id ] =
1474
+									$line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1475
+							}
1476
+						}
1477
+					}
1478
+					break;
1479
+			}
1480
+		}
1481
+		return $running_totals;
1482
+	}
1483
+
1484
+
1485
+	/**
1486
+	 * @param \EE_Line_Item $total_line_item
1487
+	 * @param \EE_Line_Item $ticket_line_item
1488
+	 * @return float | null
1489
+	 * @throws \OutOfRangeException
1490
+	 */
1491
+	public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item)
1492
+	{
1493
+		static $final_prices_per_ticket_line_item = array();
1494
+		if (empty($final_prices_per_ticket_line_item)) {
1495
+			$final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1496
+				$total_line_item
1497
+			);
1498
+		}
1499
+		// ok now find this new registration's final price
1500
+		if (isset($final_prices_per_ticket_line_item[ $ticket_line_item->ID() ])) {
1501
+			return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1502
+		}
1503
+		$message = sprintf(
1504
+			__(
1505
+				'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1506
+				'event_espresso'
1507
+			),
1508
+			$ticket_line_item->ID()
1509
+		);
1510
+		if (WP_DEBUG) {
1511
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1512
+			throw new \OutOfRangeException($message);
1513
+		} else {
1514
+			EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1515
+		}
1516
+		return null;
1517
+	}
1518
+
1519
+
1520
+	/**
1521
+	 * Creates a duplicate of the line item tree, except only includes billable items
1522
+	 * and the portion of line items attributed to billable things
1523
+	 *
1524
+	 * @param EE_Line_Item $line_item
1525
+	 * @param EE_Registration[] $registrations
1526
+	 * @return \EE_Line_Item
1527
+	 * @throws \EE_Error
1528
+	 */
1529
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1530
+	{
1531
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1532
+		foreach ($line_item->children() as $child_li) {
1533
+			$copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1534
+		}
1535
+		// if this is the grand total line item, make sure the totals all add up
1536
+		// (we could have duplicated this logic AS we copied the line items, but
1537
+		// it seems DRYer this way)
1538
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1539
+			$copy_li->recalculate_total_including_taxes();
1540
+		}
1541
+		return $copy_li;
1542
+	}
1543
+
1544
+
1545
+	/**
1546
+	 * Creates a new, unsaved line item from $line_item that factors in the
1547
+	 * number of billable registrations on $registrations.
1548
+	 *
1549
+	 * @param EE_Line_Item $line_item
1550
+	 * @return EE_Line_Item
1551
+	 * @throws \EE_Error
1552
+	 * @param EE_Registration[] $registrations
1553
+	 */
1554
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1555
+	{
1556
+		$new_li_fields = $line_item->model_field_array();
1557
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1558
+			$line_item->OBJ_type() === 'Ticket'
1559
+		) {
1560
+			$count = 0;
1561
+			foreach ($registrations as $registration) {
1562
+				if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1563
+					in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1564
+				) {
1565
+					$count++;
1566
+				}
1567
+			}
1568
+			$new_li_fields['LIN_quantity'] = $count;
1569
+		}
1570
+		// don't set the total. We'll leave that up to the code that calculates it
1571
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1572
+		return EE_Line_Item::new_instance($new_li_fields);
1573
+	}
1574
+
1575
+
1576
+	/**
1577
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1578
+	 * are removed, and line items with a quantity of 0
1579
+	 *
1580
+	 * @param EE_Line_Item $line_item |null
1581
+	 * @return \EE_Line_Item|null
1582
+	 * @throws \EE_Error
1583
+	 */
1584
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1585
+	{
1586
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1587
+		if ($copied_li === null) {
1588
+			return null;
1589
+		}
1590
+		// if this is an event subtotal, we want to only include it if it
1591
+		// has a non-zero total and at least one ticket line item child
1592
+		$ticket_children = 0;
1593
+		foreach ($line_item->children() as $child_li) {
1594
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1595
+			if ($child_li_copy !== null) {
1596
+				$copied_li->add_child_line_item($child_li_copy);
1597
+				if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1598
+					$child_li_copy->OBJ_type() === 'Ticket'
1599
+				) {
1600
+					$ticket_children++;
1601
+				}
1602
+			}
1603
+		}
1604
+		// if this is an event subtotal with NO ticket children
1605
+		// we basically want to ignore it
1606
+		if ($ticket_children === 0
1607
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1608
+			&& $line_item->OBJ_type() === 'Event'
1609
+			&& $line_item->total() === 0
1610
+		) {
1611
+			return null;
1612
+		}
1613
+		return $copied_li;
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1619
+	 * with a total of 0, or a subtotal of 0, returns null instead
1620
+	 *
1621
+	 * @param EE_Line_Item $line_item
1622
+	 * @return EE_Line_Item
1623
+	 * @throws \EE_Error
1624
+	 */
1625
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1626
+	{
1627
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1628
+			$line_item->OBJ_type() === 'Ticket' &&
1629
+			$line_item->quantity() === 0
1630
+		) {
1631
+			return null;
1632
+		}
1633
+		$new_li_fields = $line_item->model_field_array();
1634
+		// don't set the total. We'll leave that up to the code that calculates it
1635
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1636
+		return EE_Line_Item::new_instance($new_li_fields);
1637
+	}
1638
+
1639
+
1640
+
1641
+	/**************************************** @DEPRECATED METHODS *************************************** */
1642
+	/**
1643
+	 * @deprecated
1644
+	 * @param EE_Line_Item $total_line_item
1645
+	 * @return \EE_Line_Item
1646
+	 * @throws \EE_Error
1647
+	 */
1648
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
1649
+	{
1650
+		EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1651
+		return self::get_pre_tax_subtotal($total_line_item);
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * @deprecated
1657
+	 * @param EE_Transaction $transaction
1658
+	 * @return \EE_Line_Item
1659
+	 * @throws \EE_Error
1660
+	 */
1661
+	public static function create_default_total_line_item($transaction = null)
1662
+	{
1663
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1664
+		return self::create_total_line_item($transaction);
1665
+	}
1666
+
1667
+
1668
+	/**
1669
+	 * @deprecated
1670
+	 * @param EE_Line_Item $total_line_item
1671
+	 * @param EE_Transaction $transaction
1672
+	 * @return \EE_Line_Item
1673
+	 * @throws \EE_Error
1674
+	 */
1675
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1676
+	{
1677
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1678
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
1679
+	}
1680
+
1681
+
1682
+	/**
1683
+	 * @deprecated
1684
+	 * @param EE_Line_Item $total_line_item
1685
+	 * @param EE_Transaction $transaction
1686
+	 * @return \EE_Line_Item
1687
+	 * @throws \EE_Error
1688
+	 */
1689
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1690
+	{
1691
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1692
+		return self::create_taxes_subtotal($total_line_item, $transaction);
1693
+	}
1694
+
1695
+
1696
+	/**
1697
+	 * @deprecated
1698
+	 * @param EE_Line_Item $total_line_item
1699
+	 * @param EE_Transaction $transaction
1700
+	 * @return \EE_Line_Item
1701
+	 * @throws \EE_Error
1702
+	 */
1703
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
1704
+	{
1705
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1706
+		return self::create_event_subtotal($total_line_item, $transaction);
1707
+	}
1708 1708
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -122,13 +122,13 @@  discard block
 block discarded – undo
122 122
      */
123 123
     public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
124 124
     {
125
-        if (!$total_line_item instanceof EE_Line_Item || !$total_line_item->is_total()) {
125
+        if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
126 126
             throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
127 127
         }
128 128
         // either increment the qty for an existing ticket
129 129
         $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
130 130
         // or add a new one
131
-        if (!$line_item instanceof EE_Line_Item) {
131
+        if ( ! $line_item instanceof EE_Line_Item) {
132 132
             $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
133 133
         }
134 134
         $total_line_item->recalculate_total_including_taxes();
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
      */
178 178
     public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
179 179
     {
180
-        if (!$line_item->is_percent()) {
180
+        if ( ! $line_item->is_percent()) {
181 181
             $qty += $line_item->quantity();
182 182
             $line_item->set_quantity($qty);
183 183
             $line_item->set_total($line_item->unit_price() * $qty);
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
      */
203 203
     public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
204 204
     {
205
-        if (!$line_item->is_percent()) {
205
+        if ( ! $line_item->is_percent()) {
206 206
             $qty = $line_item->quantity() - $qty;
207 207
             $qty = max($qty, 0);
208 208
             $line_item->set_quantity($qty);
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
      */
228 228
     public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
229 229
     {
230
-        if (!$line_item->is_percent()) {
230
+        if ( ! $line_item->is_percent()) {
231 231
             $line_item->set_quantity($new_quantity);
232 232
             $line_item->set_total($line_item->unit_price() * $new_quantity);
233 233
             $line_item->save();
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
         // add $ticket to cart
264 264
         $line_item = EE_Line_Item::new_instance(array(
265 265
             'LIN_name' => $ticket->name(),
266
-            'LIN_desc' => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
266
+            'LIN_desc' => $ticket->description() !== '' ? $ticket->description().' '.$event : $event,
267 267
             'LIN_unit_price' => $ticket->price(),
268 268
             'LIN_quantity' => $qty,
269 269
             'LIN_is_taxable' => $ticket->taxable(),
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
         $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
373 373
         foreach ($ticket_line_item->children() as $child_line_item) {
374 374
             if ($child_line_item->is_sub_line_item()
375
-                && !$child_line_item->is_percent()
376
-                && !$child_line_item->is_cancellation()
375
+                && ! $child_line_item->is_percent()
376
+                && ! $child_line_item->is_cancellation()
377 377
             ) {
378 378
                 $child_line_item->set_quantity($child_line_item->quantity() - $qty);
379 379
             }
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
                 'LIN_desc' => sprintf(
396 396
                     _x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
397 397
                     $ticket_line_item->name(),
398
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
398
+                    current_time(get_option('date_format').' '.get_option('time_format'))
399 399
                 ),
400 400
                 'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
401 401
                 'LIN_quantity' => $qty,
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
         );
449 449
         $cancellation_line_item = reset($cancellation_line_item);
450 450
         // verify that this ticket was indeed previously cancelled
451
-        if (!$cancellation_line_item instanceof EE_Line_Item) {
451
+        if ( ! $cancellation_line_item instanceof EE_Line_Item) {
452 452
             return false;
453 453
         }
454 454
         if ($cancellation_line_item->quantity() > $qty) {
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
             'LIN_code' => 'taxes',
623 623
             'LIN_name' => __('Taxes', 'event_espresso'),
624 624
             'LIN_type' => EEM_Line_Item::type_tax_sub_total,
625
-            'LIN_order' => 1000,// this should always come last
625
+            'LIN_order' => 1000, // this should always come last
626 626
         ));
627 627
         $tax_line_item = apply_filters(
628 628
             'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
      */
675 675
     public static function get_event_code($event)
676 676
     {
677
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
677
+        return 'event-'.($event instanceof EE_Event ? $event->ID() : '0');
678 678
     }
679 679
 
680 680
     /**
@@ -710,13 +710,13 @@  discard block
 block discarded – undo
710 710
     public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
711 711
     {
712 712
         $first_datetime = $ticket->first_datetime();
713
-        if (!$first_datetime instanceof EE_Datetime) {
713
+        if ( ! $first_datetime instanceof EE_Datetime) {
714 714
             throw new EE_Error(
715 715
                 sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
716 716
             );
717 717
         }
718 718
         $event = $first_datetime->event();
719
-        if (!$event instanceof EE_Event) {
719
+        if ( ! $event instanceof EE_Event) {
720 720
             throw new EE_Error(
721 721
                 sprintf(
722 722
                     __('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
             );
726 726
         }
727 727
         $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
728
-        if (!$events_sub_total instanceof EE_Line_Item) {
728
+        if ( ! $events_sub_total instanceof EE_Line_Item) {
729 729
             throw new EE_Error(
730 730
                 sprintf(
731 731
                     __('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
         $found = false;
755 755
         foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
756 756
             // default event subtotal, we should only ever find this the first time this method is called
757
-            if (!$event_line_item->OBJ_ID()) {
757
+            if ( ! $event_line_item->OBJ_ID()) {
758 758
                 // let's use this! but first... set the event details
759 759
                 EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
760 760
                 $found = true;
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
                 break;
766 766
             }
767 767
         }
768
-        if (!$found) {
768
+        if ( ! $found) {
769 769
             // there is no event sub-total yet, so add it
770 770
             $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
771 771
             // create a new "event" subtotal below that
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
     public static function ensure_taxes_applied($total_line_item)
860 860
     {
861 861
         $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
862
-        if (!$taxes_subtotal->children()) {
862
+        if ( ! $taxes_subtotal->children()) {
863 863
             self::apply_taxes($total_line_item);
864 864
         }
865 865
         return $taxes_subtotal->total();
@@ -920,7 +920,7 @@  discard block
 block discarded – undo
920 920
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
921 921
 
922 922
         // check if only a single line_item_id was passed
923
-        if (!empty($line_item_codes) && !is_array($line_item_codes)) {
923
+        if ( ! empty($line_item_codes) && ! is_array($line_item_codes)) {
924 924
             // place single line_item_id in an array to appear as multiple line_item_ids
925 925
             $line_item_codes = array($line_item_codes);
926 926
         }
@@ -1021,7 +1021,7 @@  discard block
 block discarded – undo
1021 1021
         if ($code_substring_for_whitelist !== null) {
1022 1022
             $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1023 1023
         }
1024
-        if (!$whitelisted && $line_item->is_line_item()) {
1024
+        if ( ! $whitelisted && $line_item->is_line_item()) {
1025 1025
             $line_item->set_is_taxable($taxable);
1026 1026
         }
1027 1027
         foreach ($line_item->children() as $child_line_item) {
@@ -1321,7 +1321,7 @@  discard block
 block discarded – undo
1321 1321
     public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1322 1322
     {
1323 1323
         echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1324
-        if (!$indentation) {
1324
+        if ( ! $indentation) {
1325 1325
             echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1326 1326
         }
1327 1327
         for ($i = 0; $i < $indentation; $i++) {
@@ -1332,10 +1332,10 @@  discard block
 block discarded – undo
1332 1332
             if ($line_item->is_percent()) {
1333 1333
                 $breakdown = "{$line_item->percent()}%";
1334 1334
             } else {
1335
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1335
+                $breakdown = '$'."{$line_item->unit_price()} x {$line_item->quantity()}";
1336 1336
             }
1337 1337
         }
1338
-        echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1338
+        echo $line_item->name()." [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ".'$'."{$line_item->total()}";
1339 1339
         if ($breakdown) {
1340 1340
             echo " ( {$breakdown} )";
1341 1341
         }
@@ -1386,10 +1386,10 @@  discard block
 block discarded – undo
1386 1386
     public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array())
1387 1387
     {
1388 1388
         // init running grand total if not already
1389
-        if (!isset($running_totals['total'])) {
1389
+        if ( ! isset($running_totals['total'])) {
1390 1390
             $running_totals['total'] = 0;
1391 1391
         }
1392
-        if (!isset($running_totals['taxable'])) {
1392
+        if ( ! isset($running_totals['taxable'])) {
1393 1393
             $running_totals['taxable'] = array('total' => 0);
1394 1394
         }
1395 1395
         foreach ($line_item->children() as $child_line_item) {
@@ -1415,8 +1415,8 @@  discard block
 block discarded – undo
1415 1415
                         if ($line_item_id === 'taxable') {
1416 1416
                             continue;
1417 1417
                         }
1418
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1419
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1418
+                        $taxable_total = $running_totals['taxable'][$line_item_id];
1419
+                        $running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1420 1420
                     }
1421 1421
                     break;
1422 1422
 
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
                     // ticket line items or ????
1425 1425
                     if ($child_line_item->OBJ_type() === 'Ticket') {
1426 1426
                         // kk it's a ticket
1427
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1427
+                        if (isset($running_totals[$child_line_item->ID()])) {
1428 1428
                             // huh? that shouldn't happen.
1429 1429
                             $running_totals['total'] += $child_line_item->total();
1430 1430
                         } else {
@@ -1435,18 +1435,18 @@  discard block
 block discarded – undo
1435 1435
                                 $taxable_amount = 0;
1436 1436
                             }
1437 1437
                             // are we only calculating totals for some tickets?
1438
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1439
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1440
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1438
+                            if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1439
+                                $quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1440
+                                $running_totals[$child_line_item->ID()] = $quantity
1441 1441
                                     ? $child_line_item->unit_price()
1442 1442
                                     : 0;
1443
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1443
+                                $running_totals['taxable'][$child_line_item->ID()] = $quantity
1444 1444
                                     ? $taxable_amount
1445 1445
                                     : 0;
1446 1446
                             } else {
1447 1447
                                 $quantity = $child_line_item->quantity();
1448
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1449
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1448
+                                $running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1449
+                                $running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1450 1450
                             }
1451 1451
                             $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1452 1452
                             $running_totals['total'] += $child_line_item->unit_price() * $quantity;
@@ -1466,12 +1466,12 @@  discard block
 block discarded – undo
1466 1466
                             }
1467 1467
                             // update the running totals
1468 1468
                             // yes this actually even works for the running grand total!
1469
-                            $running_totals[ $line_item_id ] =
1469
+                            $running_totals[$line_item_id] =
1470 1470
                                 $line_items_percent_of_running_total * $this_running_total;
1471 1471
 
1472 1472
                             if ($child_line_item->is_taxable()) {
1473
-                                $running_totals['taxable'][ $line_item_id ] =
1474
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1473
+                                $running_totals['taxable'][$line_item_id] =
1474
+                                    $line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1475 1475
                             }
1476 1476
                         }
1477 1477
                     }
@@ -1497,8 +1497,8 @@  discard block
 block discarded – undo
1497 1497
             );
1498 1498
         }
1499 1499
         // ok now find this new registration's final price
1500
-        if (isset($final_prices_per_ticket_line_item[ $ticket_line_item->ID() ])) {
1501
-            return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1500
+        if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1501
+            return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1502 1502
         }
1503 1503
         $message = sprintf(
1504 1504
             __(
@@ -1508,7 +1508,7 @@  discard block
 block discarded – undo
1508 1508
             $ticket_line_item->ID()
1509 1509
         );
1510 1510
         if (WP_DEBUG) {
1511
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1511
+            $message .= '<br>'.print_r($final_prices_per_ticket_line_item, true);
1512 1512
             throw new \OutOfRangeException($message);
1513 1513
         } else {
1514 1514
             EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
Please login to merge, or discard this patch.
core/helpers/EEH_DTT_Helper.helper.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -197,8 +197,8 @@  discard block
 block discarded – undo
197 197
      * Get Timezone Offset for given timezone object.
198 198
      *
199 199
      * @param DateTimeZone $date_time_zone
200
-     * @param null         $time
201
-     * @return mixed
200
+     * @param integer|null         $time
201
+     * @return integer
202 202
      * @throws InvalidArgumentException
203 203
      * @throws InvalidDataTypeException
204 204
      * @throws InvalidInterfaceException
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
      * @param  DateTime   $DateTime DateTime object
321 321
      * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
322 322
      *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
323
-     * @param  int|string $value    What you want to increment the date by
323
+     * @param  integer $value    What you want to increment the date by
324 324
      * @param  string     $operand  What operand you wish to use for the calculation
325 325
      * @return DateTime return whatever type came in.
326 326
      * @throws Exception
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
      * this method will add that "1" into your date regardless of the format.
857 857
      *
858 858
      * @param string $month
859
-     * @return string
859
+     * @return integer
860 860
      */
861 861
     public static function first_of_month_timestamp($month = '')
862 862
     {
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
     /**
1005 1005
      * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1006 1006
      *
1007
-     * @param int|WP_User $user_id
1007
+     * @param integer $user_id
1008 1008
      * @return string
1009 1009
      */
1010 1010
     public static function get_user_locale($user_id = 0)
Please login to merge, or discard this patch.
Indentation   +981 added lines, -981 removed lines patch added patch discarded remove patch
@@ -17,1043 +17,1043 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * return the timezone set for the WP install
22
-     *
23
-     * @return string valid timezone string for PHP DateTimeZone() class
24
-     * @throws InvalidArgumentException
25
-     * @throws InvalidDataTypeException
26
-     * @throws InvalidInterfaceException
27
-     */
28
-    public static function get_timezone()
29
-    {
30
-        return EEH_DTT_Helper::get_valid_timezone_string();
31
-    }
20
+	/**
21
+	 * return the timezone set for the WP install
22
+	 *
23
+	 * @return string valid timezone string for PHP DateTimeZone() class
24
+	 * @throws InvalidArgumentException
25
+	 * @throws InvalidDataTypeException
26
+	 * @throws InvalidInterfaceException
27
+	 */
28
+	public static function get_timezone()
29
+	{
30
+		return EEH_DTT_Helper::get_valid_timezone_string();
31
+	}
32 32
 
33 33
 
34
-    /**
35
-     * get_valid_timezone_string
36
-     *    ensures that a valid timezone string is returned
37
-     *
38
-     * @param string $timezone_string
39
-     * @return string
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     */
44
-    public static function get_valid_timezone_string($timezone_string = '')
45
-    {
46
-        return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
-    }
34
+	/**
35
+	 * get_valid_timezone_string
36
+	 *    ensures that a valid timezone string is returned
37
+	 *
38
+	 * @param string $timezone_string
39
+	 * @return string
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 */
44
+	public static function get_valid_timezone_string($timezone_string = '')
45
+	{
46
+		return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
-     *
53
-     * @static
54
-     * @param  string $timezone_string Timezone string to check
55
-     * @param bool    $throw_error
56
-     * @return bool
57
-     * @throws InvalidArgumentException
58
-     * @throws InvalidDataTypeException
59
-     * @throws InvalidInterfaceException
60
-     */
61
-    public static function validate_timezone($timezone_string, $throw_error = true)
62
-    {
63
-        return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
-    }
50
+	/**
51
+	 * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
+	 *
53
+	 * @static
54
+	 * @param  string $timezone_string Timezone string to check
55
+	 * @param bool    $throw_error
56
+	 * @return bool
57
+	 * @throws InvalidArgumentException
58
+	 * @throws InvalidDataTypeException
59
+	 * @throws InvalidInterfaceException
60
+	 */
61
+	public static function validate_timezone($timezone_string, $throw_error = true)
62
+	{
63
+		return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * This returns a string that can represent the provided gmt offset in format that can be passed into
69
-     * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
-     *
71
-     * @param float|string $gmt_offset
72
-     * @return string
73
-     * @throws InvalidArgumentException
74
-     * @throws InvalidDataTypeException
75
-     * @throws InvalidInterfaceException
76
-     */
77
-    public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
-    {
79
-        return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
-    }
67
+	/**
68
+	 * This returns a string that can represent the provided gmt offset in format that can be passed into
69
+	 * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
+	 *
71
+	 * @param float|string $gmt_offset
72
+	 * @return string
73
+	 * @throws InvalidArgumentException
74
+	 * @throws InvalidDataTypeException
75
+	 * @throws InvalidInterfaceException
76
+	 */
77
+	public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
+	{
79
+		return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
+	}
81 81
 
82 82
 
83
-    /**
84
-     * Gets the site's GMT offset based on either the timezone string
85
-     * (in which case teh gmt offset will vary depending on the location's
86
-     * observance of daylight savings time) or the gmt_offset wp option
87
-     *
88
-     * @return int seconds offset
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     */
93
-    public static function get_site_timezone_gmt_offset()
94
-    {
95
-        return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
-    }
83
+	/**
84
+	 * Gets the site's GMT offset based on either the timezone string
85
+	 * (in which case teh gmt offset will vary depending on the location's
86
+	 * observance of daylight savings time) or the gmt_offset wp option
87
+	 *
88
+	 * @return int seconds offset
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 */
93
+	public static function get_site_timezone_gmt_offset()
94
+	{
95
+		return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
+	}
97 97
 
98 98
 
99
-    /**
100
-     * Depending on PHP version,
101
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
103
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
-     *
105
-     * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
-     *                          removed in a future version of EE.
107
-     * @param int $gmt_offset
108
-     * @return int
109
-     * @throws InvalidArgumentException
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     */
113
-    public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
-    {
115
-        return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
-    }
99
+	/**
100
+	 * Depending on PHP version,
101
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
103
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
+	 *
105
+	 * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
+	 *                          removed in a future version of EE.
107
+	 * @param int $gmt_offset
108
+	 * @return int
109
+	 * @throws InvalidArgumentException
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 */
113
+	public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
+	{
115
+		return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * get_timezone_string_from_abbreviations_list
121
-     *
122
-     * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
-     *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
-     * @param int  $gmt_offset
125
-     * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
-     * @return string
127
-     * @throws EE_Error
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     */
132
-    public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
-    {
134
-        $gmt_offset =  (int) $gmt_offset;
135
-        /** @var array[] $abbreviations */
136
-        $abbreviations = DateTimeZone::listAbbreviations();
137
-        foreach ($abbreviations as $abbreviation) {
138
-            foreach ($abbreviation as $timezone) {
139
-                if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
-                    try {
141
-                        $offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
-                        if ($offset !== $gmt_offset) {
143
-                            continue;
144
-                        }
145
-                        return $timezone['timezone_id'];
146
-                    } catch (Exception $e) {
147
-                        continue;
148
-                    }
149
-                }
150
-            }
151
-        }
152
-        // if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
-        if ($coerce === true) {
154
-            $timezone_string = self::get_timezone_string_from_abbreviations_list(
155
-                self::adjust_invalid_gmt_offsets($gmt_offset),
156
-                false
157
-            );
158
-            if ($timezone_string) {
159
-                return $timezone_string;
160
-            }
161
-        }
162
-        throw new EE_Error(
163
-            sprintf(
164
-                esc_html__(
165
-                    'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
-                    'event_espresso'
167
-                ),
168
-                $gmt_offset / HOUR_IN_SECONDS,
169
-                '<a href="http://www.php.net/manual/en/timezones.php">',
170
-                '</a>'
171
-            )
172
-        );
173
-    }
119
+	/**
120
+	 * get_timezone_string_from_abbreviations_list
121
+	 *
122
+	 * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
+	 *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
+	 * @param int  $gmt_offset
125
+	 * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 */
132
+	public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
+	{
134
+		$gmt_offset =  (int) $gmt_offset;
135
+		/** @var array[] $abbreviations */
136
+		$abbreviations = DateTimeZone::listAbbreviations();
137
+		foreach ($abbreviations as $abbreviation) {
138
+			foreach ($abbreviation as $timezone) {
139
+				if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
+					try {
141
+						$offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
+						if ($offset !== $gmt_offset) {
143
+							continue;
144
+						}
145
+						return $timezone['timezone_id'];
146
+					} catch (Exception $e) {
147
+						continue;
148
+					}
149
+				}
150
+			}
151
+		}
152
+		// if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
+		if ($coerce === true) {
154
+			$timezone_string = self::get_timezone_string_from_abbreviations_list(
155
+				self::adjust_invalid_gmt_offsets($gmt_offset),
156
+				false
157
+			);
158
+			if ($timezone_string) {
159
+				return $timezone_string;
160
+			}
161
+		}
162
+		throw new EE_Error(
163
+			sprintf(
164
+				esc_html__(
165
+					'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
+					'event_espresso'
167
+				),
168
+				$gmt_offset / HOUR_IN_SECONDS,
169
+				'<a href="http://www.php.net/manual/en/timezones.php">',
170
+				'</a>'
171
+			)
172
+		);
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * Get Timezone Transitions
178
-     *
179
-     * @param DateTimeZone $date_time_zone
180
-     * @param int|null     $time
181
-     * @param bool         $first_only
182
-     * @return array
183
-     * @throws InvalidArgumentException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
-    {
189
-        return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
-    }
176
+	/**
177
+	 * Get Timezone Transitions
178
+	 *
179
+	 * @param DateTimeZone $date_time_zone
180
+	 * @param int|null     $time
181
+	 * @param bool         $first_only
182
+	 * @return array
183
+	 * @throws InvalidArgumentException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
+	{
189
+		return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * Get Timezone Offset for given timezone object.
195
-     *
196
-     * @param DateTimeZone $date_time_zone
197
-     * @param null         $time
198
-     * @return mixed
199
-     * @throws InvalidArgumentException
200
-     * @throws InvalidDataTypeException
201
-     * @throws InvalidInterfaceException
202
-     */
203
-    public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
-    {
205
-        return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
-    }
193
+	/**
194
+	 * Get Timezone Offset for given timezone object.
195
+	 *
196
+	 * @param DateTimeZone $date_time_zone
197
+	 * @param null         $time
198
+	 * @return mixed
199
+	 * @throws InvalidArgumentException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws InvalidInterfaceException
202
+	 */
203
+	public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
+	{
205
+		return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
+	}
207 207
 
208 208
 
209
-    /**
210
-     * Prints a select input for the given timezone string.
211
-     * @param string $timezone_string
212
-     * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidInterfaceException
216
-     */
217
-    public static function timezone_select_input($timezone_string = '')
218
-    {
219
-        self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
-    }
209
+	/**
210
+	 * Prints a select input for the given timezone string.
211
+	 * @param string $timezone_string
212
+	 * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidInterfaceException
216
+	 */
217
+	public static function timezone_select_input($timezone_string = '')
218
+	{
219
+		self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
+	}
221 221
 
222 222
 
223
-    /**
224
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
-     * the site is used.
227
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
-     * computed timestamp (i.e. date_i18n() )
229
-     *
230
-     * @param int    $unix_timestamp                  if 0, then time() will be used.
231
-     * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
-     *                                                site will be used.
233
-     * @return int $unix_timestamp with the offset applied for the given timezone.
234
-     * @throws InvalidArgumentException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     */
238
-    public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
-    {
240
-        return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
-    }
223
+	/**
224
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
+	 * the site is used.
227
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
+	 * computed timestamp (i.e. date_i18n() )
229
+	 *
230
+	 * @param int    $unix_timestamp                  if 0, then time() will be used.
231
+	 * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
+	 *                                                site will be used.
233
+	 * @return int $unix_timestamp with the offset applied for the given timezone.
234
+	 * @throws InvalidArgumentException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 */
238
+	public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
+	{
240
+		return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
+	}
242 242
 
243 243
 
244
-    /**
245
-     *    _set_date_time_field
246
-     *    modifies EE_Base_Class EE_Datetime_Field objects
247
-     *
248
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
249
-     * @param    DateTime    $DateTime            PHP DateTime object
250
-     * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
-     * @return EE_Base_Class
252
-     * @throws EE_Error
253
-     */
254
-    protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
-    {
256
-        // grab current datetime format
257
-        $current_format = $obj->get_format();
258
-        // set new full timestamp format
259
-        $obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
-        $obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
-        // set the new date value using a full timestamp format so that no data is lost
262
-        $obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
-        // reset datetime formats
264
-        $obj->set_date_format($current_format[0]);
265
-        $obj->set_time_format($current_format[1]);
266
-        return $obj;
267
-    }
244
+	/**
245
+	 *    _set_date_time_field
246
+	 *    modifies EE_Base_Class EE_Datetime_Field objects
247
+	 *
248
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
249
+	 * @param    DateTime    $DateTime            PHP DateTime object
250
+	 * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
+	 * @return EE_Base_Class
252
+	 * @throws EE_Error
253
+	 */
254
+	protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
+	{
256
+		// grab current datetime format
257
+		$current_format = $obj->get_format();
258
+		// set new full timestamp format
259
+		$obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
+		$obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
+		// set the new date value using a full timestamp format so that no data is lost
262
+		$obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
+		// reset datetime formats
264
+		$obj->set_date_format($current_format[0]);
265
+		$obj->set_time_format($current_format[1]);
266
+		return $obj;
267
+	}
268 268
 
269 269
 
270
-    /**
271
-     *    date_time_add
272
-     *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
-     *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
-     *
275
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
276
-     * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
-     * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
-     *                                            minutes, seconds) defaults to years
279
-     * @param  integer       $value               what you want to increment the time by
280
-     * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
-     *                                            (chaining)
282
-     * @throws EE_Error
283
-     * @throws Exception
284
-     */
285
-    public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
-    {
287
-        // get the raw UTC date.
288
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
289
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
-    }
270
+	/**
271
+	 *    date_time_add
272
+	 *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
+	 *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
+	 *
275
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
276
+	 * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
+	 * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
+	 *                                            minutes, seconds) defaults to years
279
+	 * @param  integer       $value               what you want to increment the time by
280
+	 * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
+	 *                                            (chaining)
282
+	 * @throws EE_Error
283
+	 * @throws Exception
284
+	 */
285
+	public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
+	{
287
+		// get the raw UTC date.
288
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
289
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
+	}
292 292
 
293 293
 
294
-    /**
295
-     *    date_time_subtract
296
-     *    same as date_time_add except subtracting value instead of adding.
297
-     *
298
-     * @param EE_Base_Class $obj
299
-     * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
-     * @param string        $period
301
-     * @param int           $value
302
-     * @return EE_Base_Class
303
-     * @throws EE_Error
304
-     * @throws Exception
305
-     */
306
-    public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
-    {
308
-        // get the raw UTC date
309
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
310
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
-    }
294
+	/**
295
+	 *    date_time_subtract
296
+	 *    same as date_time_add except subtracting value instead of adding.
297
+	 *
298
+	 * @param EE_Base_Class $obj
299
+	 * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
+	 * @param string        $period
301
+	 * @param int           $value
302
+	 * @return EE_Base_Class
303
+	 * @throws EE_Error
304
+	 * @throws Exception
305
+	 */
306
+	public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
+	{
308
+		// get the raw UTC date
309
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
310
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
+	}
313 313
 
314 314
 
315
-    /**
316
-     * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
-     *
318
-     * @param  DateTime   $DateTime DateTime object
319
-     * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
-     *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
-     * @param  int|string $value    What you want to increment the date by
322
-     * @param  string     $operand  What operand you wish to use for the calculation
323
-     * @return DateTime return whatever type came in.
324
-     * @throws Exception
325
-     * @throws EE_Error
326
-     */
327
-    protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
-    {
329
-        if (! $DateTime instanceof DateTime) {
330
-            throw new EE_Error(
331
-                sprintf(
332
-                    esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
-                    print_r($DateTime, true)
334
-                )
335
-            );
336
-        }
337
-        switch ($period) {
338
-            case 'years':
339
-                $value = 'P' . $value . 'Y';
340
-                break;
341
-            case 'months':
342
-                $value = 'P' . $value . 'M';
343
-                break;
344
-            case 'weeks':
345
-                $value = 'P' . $value . 'W';
346
-                break;
347
-            case 'days':
348
-                $value = 'P' . $value . 'D';
349
-                break;
350
-            case 'hours':
351
-                $value = 'PT' . $value . 'H';
352
-                break;
353
-            case 'minutes':
354
-                $value = 'PT' . $value . 'M';
355
-                break;
356
-            case 'seconds':
357
-                $value = 'PT' . $value . 'S';
358
-                break;
359
-        }
360
-        switch ($operand) {
361
-            case '+':
362
-                $DateTime->add(new DateInterval($value));
363
-                break;
364
-            case '-':
365
-                $DateTime->sub(new DateInterval($value));
366
-                break;
367
-        }
368
-        return $DateTime;
369
-    }
315
+	/**
316
+	 * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
+	 *
318
+	 * @param  DateTime   $DateTime DateTime object
319
+	 * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
+	 *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
+	 * @param  int|string $value    What you want to increment the date by
322
+	 * @param  string     $operand  What operand you wish to use for the calculation
323
+	 * @return DateTime return whatever type came in.
324
+	 * @throws Exception
325
+	 * @throws EE_Error
326
+	 */
327
+	protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
+	{
329
+		if (! $DateTime instanceof DateTime) {
330
+			throw new EE_Error(
331
+				sprintf(
332
+					esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
+					print_r($DateTime, true)
334
+				)
335
+			);
336
+		}
337
+		switch ($period) {
338
+			case 'years':
339
+				$value = 'P' . $value . 'Y';
340
+				break;
341
+			case 'months':
342
+				$value = 'P' . $value . 'M';
343
+				break;
344
+			case 'weeks':
345
+				$value = 'P' . $value . 'W';
346
+				break;
347
+			case 'days':
348
+				$value = 'P' . $value . 'D';
349
+				break;
350
+			case 'hours':
351
+				$value = 'PT' . $value . 'H';
352
+				break;
353
+			case 'minutes':
354
+				$value = 'PT' . $value . 'M';
355
+				break;
356
+			case 'seconds':
357
+				$value = 'PT' . $value . 'S';
358
+				break;
359
+		}
360
+		switch ($operand) {
361
+			case '+':
362
+				$DateTime->add(new DateInterval($value));
363
+				break;
364
+			case '-':
365
+				$DateTime->sub(new DateInterval($value));
366
+				break;
367
+		}
368
+		return $DateTime;
369
+	}
370 370
 
371 371
 
372
-    /**
373
-     * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
-     *
375
-     * @param  int     $timestamp Unix timestamp
376
-     * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
-     *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
-     * @param  integer $value     What you want to increment the date by
379
-     * @param  string  $operand   What operand you wish to use for the calculation
380
-     * @return int
381
-     * @throws EE_Error
382
-     */
383
-    protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
-    {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
-            throw new EE_Error(
387
-                sprintf(
388
-                    esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
-                    print_r($timestamp, true)
390
-                )
391
-            );
392
-        }
393
-        switch ($period) {
394
-            case 'years':
395
-                $value = YEAR_IN_SECONDS * $value;
396
-                break;
397
-            case 'months':
398
-                $value = YEAR_IN_SECONDS / 12 * $value;
399
-                break;
400
-            case 'weeks':
401
-                $value = WEEK_IN_SECONDS * $value;
402
-                break;
403
-            case 'days':
404
-                $value = DAY_IN_SECONDS * $value;
405
-                break;
406
-            case 'hours':
407
-                $value = HOUR_IN_SECONDS * $value;
408
-                break;
409
-            case 'minutes':
410
-                $value = MINUTE_IN_SECONDS * $value;
411
-                break;
412
-        }
413
-        switch ($operand) {
414
-            case '+':
415
-                $timestamp += $value;
416
-                break;
417
-            case '-':
418
-                $timestamp -= $value;
419
-                break;
420
-        }
421
-        return $timestamp;
422
-    }
372
+	/**
373
+	 * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
+	 *
375
+	 * @param  int     $timestamp Unix timestamp
376
+	 * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
+	 *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
+	 * @param  integer $value     What you want to increment the date by
379
+	 * @param  string  $operand   What operand you wish to use for the calculation
380
+	 * @return int
381
+	 * @throws EE_Error
382
+	 */
383
+	protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
+	{
385
+		if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
+			throw new EE_Error(
387
+				sprintf(
388
+					esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
+					print_r($timestamp, true)
390
+				)
391
+			);
392
+		}
393
+		switch ($period) {
394
+			case 'years':
395
+				$value = YEAR_IN_SECONDS * $value;
396
+				break;
397
+			case 'months':
398
+				$value = YEAR_IN_SECONDS / 12 * $value;
399
+				break;
400
+			case 'weeks':
401
+				$value = WEEK_IN_SECONDS * $value;
402
+				break;
403
+			case 'days':
404
+				$value = DAY_IN_SECONDS * $value;
405
+				break;
406
+			case 'hours':
407
+				$value = HOUR_IN_SECONDS * $value;
408
+				break;
409
+			case 'minutes':
410
+				$value = MINUTE_IN_SECONDS * $value;
411
+				break;
412
+		}
413
+		switch ($operand) {
414
+			case '+':
415
+				$timestamp += $value;
416
+				break;
417
+			case '-':
418
+				$timestamp -= $value;
419
+				break;
420
+		}
421
+		return $timestamp;
422
+	}
423 423
 
424 424
 
425
-    /**
426
-     * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
-     * parameters and returns the new timestamp or DateTime.
428
-     *
429
-     * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
-     * @param  string         $period                a value to indicate what interval is being used in the
431
-     *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
-     *                                               'minutes', 'seconds'. Defaults to years.
433
-     * @param  integer        $value                 What you want to increment the date by
434
-     * @param  string         $operand               What operand you wish to use for the calculation
435
-     * @return mixed string|DateTime          return whatever type came in.
436
-     * @throws Exception
437
-     * @throws EE_Error
438
-     */
439
-    public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
-    {
441
-        if ($DateTime_or_timestamp instanceof DateTime) {
442
-            return EEH_DTT_Helper::_modify_datetime_object(
443
-                $DateTime_or_timestamp,
444
-                $period,
445
-                $value,
446
-                $operand
447
-            );
448
-        }
449
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
-            return EEH_DTT_Helper::_modify_timestamp(
451
-                $DateTime_or_timestamp,
452
-                $period,
453
-                $value,
454
-                $operand
455
-            );
456
-        }
457
-        // error
458
-        return $DateTime_or_timestamp;
459
-    }
425
+	/**
426
+	 * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
+	 * parameters and returns the new timestamp or DateTime.
428
+	 *
429
+	 * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
+	 * @param  string         $period                a value to indicate what interval is being used in the
431
+	 *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
+	 *                                               'minutes', 'seconds'. Defaults to years.
433
+	 * @param  integer        $value                 What you want to increment the date by
434
+	 * @param  string         $operand               What operand you wish to use for the calculation
435
+	 * @return mixed string|DateTime          return whatever type came in.
436
+	 * @throws Exception
437
+	 * @throws EE_Error
438
+	 */
439
+	public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
+	{
441
+		if ($DateTime_or_timestamp instanceof DateTime) {
442
+			return EEH_DTT_Helper::_modify_datetime_object(
443
+				$DateTime_or_timestamp,
444
+				$period,
445
+				$value,
446
+				$operand
447
+			);
448
+		}
449
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
+			return EEH_DTT_Helper::_modify_timestamp(
451
+				$DateTime_or_timestamp,
452
+				$period,
453
+				$value,
454
+				$operand
455
+			);
456
+		}
457
+		// error
458
+		return $DateTime_or_timestamp;
459
+	}
460 460
 
461 461
 
462
-    /**
463
-     * The purpose of this helper method is to receive an incoming format string in php date/time format
464
-     * and spit out the js and moment.js equivalent formats.
465
-     * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
-     * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
-     * time picker.
468
-     *
469
-     * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
-     * @param string $date_format_string
471
-     * @param string $time_format_string
472
-     * @return array
473
-     *              array(
474
-     *              'js' => array (
475
-     *              'date' => //date format
476
-     *              'time' => //time format
477
-     *              ),
478
-     *              'moment' => //date and time format.
479
-     *              )
480
-     */
481
-    public static function convert_php_to_js_and_moment_date_formats(
482
-        $date_format_string = null,
483
-        $time_format_string = null
484
-    ) {
485
-        if ($date_format_string === null) {
486
-            $date_format_string = (string) get_option('date_format');
487
-        }
488
-        if ($time_format_string === null) {
489
-            $time_format_string = (string) get_option('time_format');
490
-        }
491
-        $date_format = self::_php_to_js_moment_converter($date_format_string);
492
-        $time_format = self::_php_to_js_moment_converter($time_format_string);
493
-        return array(
494
-            'js'     => array(
495
-                'date' => $date_format['js'],
496
-                'time' => $time_format['js'],
497
-            ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
-            'moment_split' => array(
500
-                'date' => $date_format['moment'],
501
-                'time' => $time_format['moment']
502
-            )
503
-        );
504
-    }
462
+	/**
463
+	 * The purpose of this helper method is to receive an incoming format string in php date/time format
464
+	 * and spit out the js and moment.js equivalent formats.
465
+	 * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
+	 * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
+	 * time picker.
468
+	 *
469
+	 * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
+	 * @param string $date_format_string
471
+	 * @param string $time_format_string
472
+	 * @return array
473
+	 *              array(
474
+	 *              'js' => array (
475
+	 *              'date' => //date format
476
+	 *              'time' => //time format
477
+	 *              ),
478
+	 *              'moment' => //date and time format.
479
+	 *              )
480
+	 */
481
+	public static function convert_php_to_js_and_moment_date_formats(
482
+		$date_format_string = null,
483
+		$time_format_string = null
484
+	) {
485
+		if ($date_format_string === null) {
486
+			$date_format_string = (string) get_option('date_format');
487
+		}
488
+		if ($time_format_string === null) {
489
+			$time_format_string = (string) get_option('time_format');
490
+		}
491
+		$date_format = self::_php_to_js_moment_converter($date_format_string);
492
+		$time_format = self::_php_to_js_moment_converter($time_format_string);
493
+		return array(
494
+			'js'     => array(
495
+				'date' => $date_format['js'],
496
+				'time' => $time_format['js'],
497
+			),
498
+			'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
+			'moment_split' => array(
500
+				'date' => $date_format['moment'],
501
+				'time' => $time_format['moment']
502
+			)
503
+		);
504
+	}
505 505
 
506 506
 
507
-    /**
508
-     * This converts incoming format string into js and moment variations.
509
-     *
510
-     * @param string $format_string incoming php format string
511
-     * @return array js and moment formats.
512
-     */
513
-    protected static function _php_to_js_moment_converter($format_string)
514
-    {
515
-        /**
516
-         * This is a map of symbols for formats.
517
-         * The index is the php symbol, the equivalent values are in the array.
518
-         *
519
-         * @var array
520
-         */
521
-        $symbols_map          = array(
522
-            // Day
523
-            // 01
524
-            'd' => array(
525
-                'js'     => 'dd',
526
-                'moment' => 'DD',
527
-            ),
528
-            // Mon
529
-            'D' => array(
530
-                'js'     => 'D',
531
-                'moment' => 'ddd',
532
-            ),
533
-            // 1,2,...31
534
-            'j' => array(
535
-                'js'     => 'd',
536
-                'moment' => 'D',
537
-            ),
538
-            // Monday
539
-            'l' => array(
540
-                'js'     => 'DD',
541
-                'moment' => 'dddd',
542
-            ),
543
-            // ISO numeric representation of the day of the week (1-6)
544
-            'N' => array(
545
-                'js'     => '',
546
-                'moment' => 'E',
547
-            ),
548
-            // st,nd.rd
549
-            'S' => array(
550
-                'js'     => '',
551
-                'moment' => 'o',
552
-            ),
553
-            // numeric representation of day of week (0-6)
554
-            'w' => array(
555
-                'js'     => '',
556
-                'moment' => 'd',
557
-            ),
558
-            // day of year starting from 0 (0-365)
559
-            'z' => array(
560
-                'js'     => 'o',
561
-                'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
-            ),
563
-            // Week
564
-            // ISO-8601 week number of year (weeks starting on monday)
565
-            'W' => array(
566
-                'js'     => '',
567
-                'moment' => 'w',
568
-            ),
569
-            // Month
570
-            // January...December
571
-            'F' => array(
572
-                'js'     => 'MM',
573
-                'moment' => 'MMMM',
574
-            ),
575
-            // 01...12
576
-            'm' => array(
577
-                'js'     => 'mm',
578
-                'moment' => 'MM',
579
-            ),
580
-            // Jan...Dec
581
-            'M' => array(
582
-                'js'     => 'M',
583
-                'moment' => 'MMM',
584
-            ),
585
-            // 1-12
586
-            'n' => array(
587
-                'js'     => 'm',
588
-                'moment' => 'M',
589
-            ),
590
-            // number of days in given month
591
-            't' => array(
592
-                'js'     => '',
593
-                'moment' => '',
594
-            ),
595
-            // Year
596
-            // whether leap year or not 1/0
597
-            'L' => array(
598
-                'js'     => '',
599
-                'moment' => '',
600
-            ),
601
-            // ISO-8601 year number
602
-            'o' => array(
603
-                'js'     => '',
604
-                'moment' => 'GGGG',
605
-            ),
606
-            // 1999...2003
607
-            'Y' => array(
608
-                'js'     => 'yy',
609
-                'moment' => 'YYYY',
610
-            ),
611
-            // 99...03
612
-            'y' => array(
613
-                'js'     => 'y',
614
-                'moment' => 'YY',
615
-            ),
616
-            // Time
617
-            // am/pm
618
-            'a' => array(
619
-                'js'     => 'tt',
620
-                'moment' => 'a',
621
-            ),
622
-            // AM/PM
623
-            'A' => array(
624
-                'js'     => 'TT',
625
-                'moment' => 'A',
626
-            ),
627
-            // Swatch Internet Time?!?
628
-            'B' => array(
629
-                'js'     => '',
630
-                'moment' => '',
631
-            ),
632
-            // 1...12
633
-            'g' => array(
634
-                'js'     => 'h',
635
-                'moment' => 'h',
636
-            ),
637
-            // 0...23
638
-            'G' => array(
639
-                'js'     => 'H',
640
-                'moment' => 'H',
641
-            ),
642
-            // 01...12
643
-            'h' => array(
644
-                'js'     => 'hh',
645
-                'moment' => 'hh',
646
-            ),
647
-            // 00...23
648
-            'H' => array(
649
-                'js'     => 'HH',
650
-                'moment' => 'HH',
651
-            ),
652
-            // 00..59
653
-            'i' => array(
654
-                'js'     => 'mm',
655
-                'moment' => 'mm',
656
-            ),
657
-            // seconds... 00...59
658
-            's' => array(
659
-                'js'     => 'ss',
660
-                'moment' => 'ss',
661
-            ),
662
-            // microseconds
663
-            'u' => array(
664
-                'js'     => '',
665
-                'moment' => '',
666
-            ),
667
-        );
668
-        $jquery_ui_format     = '';
669
-        $moment_format        = '';
670
-        $escaping             = false;
671
-        $format_string_length = strlen($format_string);
672
-        for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
674
-            if ($char === '\\') { // PHP date format escaping character
675
-                $i++;
676
-                if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
679
-                } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
682
-                }
683
-                $escaping = true;
684
-            } else {
685
-                if ($escaping) {
686
-                    $jquery_ui_format .= "'";
687
-                    $moment_format    .= "'";
688
-                    $escaping         = false;
689
-                }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
693
-                } else {
694
-                    $jquery_ui_format .= $char;
695
-                    $moment_format    .= $char;
696
-                }
697
-            }
698
-        }
699
-        return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
-    }
507
+	/**
508
+	 * This converts incoming format string into js and moment variations.
509
+	 *
510
+	 * @param string $format_string incoming php format string
511
+	 * @return array js and moment formats.
512
+	 */
513
+	protected static function _php_to_js_moment_converter($format_string)
514
+	{
515
+		/**
516
+		 * This is a map of symbols for formats.
517
+		 * The index is the php symbol, the equivalent values are in the array.
518
+		 *
519
+		 * @var array
520
+		 */
521
+		$symbols_map          = array(
522
+			// Day
523
+			// 01
524
+			'd' => array(
525
+				'js'     => 'dd',
526
+				'moment' => 'DD',
527
+			),
528
+			// Mon
529
+			'D' => array(
530
+				'js'     => 'D',
531
+				'moment' => 'ddd',
532
+			),
533
+			// 1,2,...31
534
+			'j' => array(
535
+				'js'     => 'd',
536
+				'moment' => 'D',
537
+			),
538
+			// Monday
539
+			'l' => array(
540
+				'js'     => 'DD',
541
+				'moment' => 'dddd',
542
+			),
543
+			// ISO numeric representation of the day of the week (1-6)
544
+			'N' => array(
545
+				'js'     => '',
546
+				'moment' => 'E',
547
+			),
548
+			// st,nd.rd
549
+			'S' => array(
550
+				'js'     => '',
551
+				'moment' => 'o',
552
+			),
553
+			// numeric representation of day of week (0-6)
554
+			'w' => array(
555
+				'js'     => '',
556
+				'moment' => 'd',
557
+			),
558
+			// day of year starting from 0 (0-365)
559
+			'z' => array(
560
+				'js'     => 'o',
561
+				'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
+			),
563
+			// Week
564
+			// ISO-8601 week number of year (weeks starting on monday)
565
+			'W' => array(
566
+				'js'     => '',
567
+				'moment' => 'w',
568
+			),
569
+			// Month
570
+			// January...December
571
+			'F' => array(
572
+				'js'     => 'MM',
573
+				'moment' => 'MMMM',
574
+			),
575
+			// 01...12
576
+			'm' => array(
577
+				'js'     => 'mm',
578
+				'moment' => 'MM',
579
+			),
580
+			// Jan...Dec
581
+			'M' => array(
582
+				'js'     => 'M',
583
+				'moment' => 'MMM',
584
+			),
585
+			// 1-12
586
+			'n' => array(
587
+				'js'     => 'm',
588
+				'moment' => 'M',
589
+			),
590
+			// number of days in given month
591
+			't' => array(
592
+				'js'     => '',
593
+				'moment' => '',
594
+			),
595
+			// Year
596
+			// whether leap year or not 1/0
597
+			'L' => array(
598
+				'js'     => '',
599
+				'moment' => '',
600
+			),
601
+			// ISO-8601 year number
602
+			'o' => array(
603
+				'js'     => '',
604
+				'moment' => 'GGGG',
605
+			),
606
+			// 1999...2003
607
+			'Y' => array(
608
+				'js'     => 'yy',
609
+				'moment' => 'YYYY',
610
+			),
611
+			// 99...03
612
+			'y' => array(
613
+				'js'     => 'y',
614
+				'moment' => 'YY',
615
+			),
616
+			// Time
617
+			// am/pm
618
+			'a' => array(
619
+				'js'     => 'tt',
620
+				'moment' => 'a',
621
+			),
622
+			// AM/PM
623
+			'A' => array(
624
+				'js'     => 'TT',
625
+				'moment' => 'A',
626
+			),
627
+			// Swatch Internet Time?!?
628
+			'B' => array(
629
+				'js'     => '',
630
+				'moment' => '',
631
+			),
632
+			// 1...12
633
+			'g' => array(
634
+				'js'     => 'h',
635
+				'moment' => 'h',
636
+			),
637
+			// 0...23
638
+			'G' => array(
639
+				'js'     => 'H',
640
+				'moment' => 'H',
641
+			),
642
+			// 01...12
643
+			'h' => array(
644
+				'js'     => 'hh',
645
+				'moment' => 'hh',
646
+			),
647
+			// 00...23
648
+			'H' => array(
649
+				'js'     => 'HH',
650
+				'moment' => 'HH',
651
+			),
652
+			// 00..59
653
+			'i' => array(
654
+				'js'     => 'mm',
655
+				'moment' => 'mm',
656
+			),
657
+			// seconds... 00...59
658
+			's' => array(
659
+				'js'     => 'ss',
660
+				'moment' => 'ss',
661
+			),
662
+			// microseconds
663
+			'u' => array(
664
+				'js'     => '',
665
+				'moment' => '',
666
+			),
667
+		);
668
+		$jquery_ui_format     = '';
669
+		$moment_format        = '';
670
+		$escaping             = false;
671
+		$format_string_length = strlen($format_string);
672
+		for ($i = 0; $i < $format_string_length; $i++) {
673
+			$char = $format_string[ $i ];
674
+			if ($char === '\\') { // PHP date format escaping character
675
+				$i++;
676
+				if ($escaping) {
677
+					$jquery_ui_format .= $format_string[ $i ];
678
+					$moment_format    .= $format_string[ $i ];
679
+				} else {
680
+					$jquery_ui_format .= '\'' . $format_string[ $i ];
681
+					$moment_format    .= $format_string[ $i ];
682
+				}
683
+				$escaping = true;
684
+			} else {
685
+				if ($escaping) {
686
+					$jquery_ui_format .= "'";
687
+					$moment_format    .= "'";
688
+					$escaping         = false;
689
+				}
690
+				if (isset($symbols_map[ $char ])) {
691
+					$jquery_ui_format .= $symbols_map[ $char ]['js'];
692
+					$moment_format    .= $symbols_map[ $char ]['moment'];
693
+				} else {
694
+					$jquery_ui_format .= $char;
695
+					$moment_format    .= $char;
696
+				}
697
+			}
698
+		}
699
+		return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
+	}
701 701
 
702 702
 
703
-    /**
704
-     * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
-     *
706
-     * @param string $format_string   Incoming format string for php date().
707
-     * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
-     *                                errors is returned.  So for client code calling, check for is_array() to
709
-     *                                indicate failed validations.
710
-     */
711
-    public static function validate_format_string($format_string)
712
-    {
713
-        $error_msg = array();
714
-        // time format checks
715
-        switch (true) {
716
-            case strpos($format_string, 'h') !== false:
717
-            case strpos($format_string, 'g') !== false:
718
-                /**
719
-                 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
-                 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
-                 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
-                 */
723
-                if (stripos($format_string, 'A') === false) {
724
-                    $error_msg[] = esc_html__(
725
-                        'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
-                        'event_espresso'
727
-                    );
728
-                }
729
-                break;
730
-        }
731
-        return empty($error_msg) ? true : $error_msg;
732
-    }
703
+	/**
704
+	 * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
+	 *
706
+	 * @param string $format_string   Incoming format string for php date().
707
+	 * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
+	 *                                errors is returned.  So for client code calling, check for is_array() to
709
+	 *                                indicate failed validations.
710
+	 */
711
+	public static function validate_format_string($format_string)
712
+	{
713
+		$error_msg = array();
714
+		// time format checks
715
+		switch (true) {
716
+			case strpos($format_string, 'h') !== false:
717
+			case strpos($format_string, 'g') !== false:
718
+				/**
719
+				 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
+				 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
+				 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
+				 */
723
+				if (stripos($format_string, 'A') === false) {
724
+					$error_msg[] = esc_html__(
725
+						'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
+						'event_espresso'
727
+					);
728
+				}
729
+				break;
730
+		}
731
+		return empty($error_msg) ? true : $error_msg;
732
+	}
733 733
 
734 734
 
735
-    /**
736
-     *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
-     *     very next day then this method will return true.
738
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
-     *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
-     *
742
-     * @param mixed $date_1
743
-     * @param mixed $date_2
744
-     * @return bool
745
-     */
746
-    public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
-    {
735
+	/**
736
+	 *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
+	 *     very next day then this method will return true.
738
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
+	 *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
+	 *
742
+	 * @param mixed $date_1
743
+	 * @param mixed $date_2
744
+	 * @return bool
745
+	 */
746
+	public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
+	{
748 748
 
749
-        if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750
-            || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751
-                || $date_2->format(
752
-                    EE_Datetime_Field::mysql_time_format
753
-                ) !== '00:00:00')
754
-        ) {
755
-            return false;
756
-        }
757
-        return $date_2->format('U') - $date_1->format('U') === 86400;
758
-    }
749
+		if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750
+			|| ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751
+				|| $date_2->format(
752
+					EE_Datetime_Field::mysql_time_format
753
+				) !== '00:00:00')
754
+		) {
755
+			return false;
756
+		}
757
+		return $date_2->format('U') - $date_1->format('U') === 86400;
758
+	}
759 759
 
760 760
 
761
-    /**
762
-     * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
763
-     * Functions.
764
-     *
765
-     * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
766
-     * @param string $field_for_interval The Database field that is the interval is applied to in the query.
767
-     * @return string
768
-     */
769
-    public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
770
-    {
771
-        try {
772
-            /** need to account for timezone offset on the selects */
773
-            $DateTimeZone = new DateTimeZone($timezone_string);
774
-        } catch (Exception $e) {
775
-            $DateTimeZone = null;
776
-        }
777
-        /**
778
-         * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
779
-         * Hence we do the calc for DateTimeZone::getOffset.
780
-         */
781
-        $offset         = $DateTimeZone instanceof DateTimeZone
782
-            ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783
-            : (float) get_option('gmt_offset');
784
-        $query_interval = $offset < 0
785
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
787
-        return $query_interval;
788
-    }
761
+	/**
762
+	 * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
763
+	 * Functions.
764
+	 *
765
+	 * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
766
+	 * @param string $field_for_interval The Database field that is the interval is applied to in the query.
767
+	 * @return string
768
+	 */
769
+	public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
770
+	{
771
+		try {
772
+			/** need to account for timezone offset on the selects */
773
+			$DateTimeZone = new DateTimeZone($timezone_string);
774
+		} catch (Exception $e) {
775
+			$DateTimeZone = null;
776
+		}
777
+		/**
778
+		 * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
779
+		 * Hence we do the calc for DateTimeZone::getOffset.
780
+		 */
781
+		$offset         = $DateTimeZone instanceof DateTimeZone
782
+			? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783
+			: (float) get_option('gmt_offset');
784
+		$query_interval = $offset < 0
785
+			? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
+			: 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
787
+		return $query_interval;
788
+	}
789 789
 
790 790
 
791
-    /**
792
-     * Retrieves the site's default timezone and returns it formatted so it's ready for display
793
-     * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
794
-     * and 'gmt_offset' WordPress options directly; or use the filter
795
-     * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
796
-     * (although note that we remove any HTML that may be added)
797
-     *
798
-     * @return string
799
-     */
800
-    public static function get_timezone_string_for_display()
801
-    {
802
-        $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
-        if (! empty($pretty_timezone)) {
804
-            return esc_html($pretty_timezone);
805
-        }
806
-        $timezone_string = get_option('timezone_string');
807
-        if ($timezone_string) {
808
-            static $mo_loaded = false;
809
-            // Load translations for continents and cities just like wp_timezone_choice does
810
-            if (! $mo_loaded) {
811
-                $locale = get_locale();
812
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
813
-                load_textdomain('continents-cities', $mofile);
814
-                $mo_loaded = true;
815
-            }
816
-            // well that was easy.
817
-            $parts = explode('/', $timezone_string);
818
-            // remove the continent
819
-            unset($parts[0]);
820
-            $t_parts = array();
821
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
822
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
823
-            // disabled because this code is copied from WordPress and is a WordPress domain
824
-            foreach ($parts as $part) {
825
-                $t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
826
-            }
827
-            return implode(' - ', $t_parts);
828
-            // phpcs:enable
829
-        }
830
-        // they haven't set the timezone string, so let's return a string like "UTC+1"
831
-        $gmt_offset = get_option('gmt_offset');
832
-        $prefix     = (int) $gmt_offset >= 0 ? '+' : '';
833
-        $parts      = explode('.', (string) $gmt_offset);
834
-        if (count($parts) === 1) {
835
-            $parts[1] = '00';
836
-        } else {
837
-            // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838
-            // to minutes, eg 30 or 15, respectively
839
-            $hour_fraction = (float) ('0.' . $parts[1]);
840
-            $parts[1]      = (string) $hour_fraction * 60;
841
-        }
842
-        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
843
-    }
791
+	/**
792
+	 * Retrieves the site's default timezone and returns it formatted so it's ready for display
793
+	 * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
794
+	 * and 'gmt_offset' WordPress options directly; or use the filter
795
+	 * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
796
+	 * (although note that we remove any HTML that may be added)
797
+	 *
798
+	 * @return string
799
+	 */
800
+	public static function get_timezone_string_for_display()
801
+	{
802
+		$pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
+		if (! empty($pretty_timezone)) {
804
+			return esc_html($pretty_timezone);
805
+		}
806
+		$timezone_string = get_option('timezone_string');
807
+		if ($timezone_string) {
808
+			static $mo_loaded = false;
809
+			// Load translations for continents and cities just like wp_timezone_choice does
810
+			if (! $mo_loaded) {
811
+				$locale = get_locale();
812
+				$mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
813
+				load_textdomain('continents-cities', $mofile);
814
+				$mo_loaded = true;
815
+			}
816
+			// well that was easy.
817
+			$parts = explode('/', $timezone_string);
818
+			// remove the continent
819
+			unset($parts[0]);
820
+			$t_parts = array();
821
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
822
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
823
+			// disabled because this code is copied from WordPress and is a WordPress domain
824
+			foreach ($parts as $part) {
825
+				$t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
826
+			}
827
+			return implode(' - ', $t_parts);
828
+			// phpcs:enable
829
+		}
830
+		// they haven't set the timezone string, so let's return a string like "UTC+1"
831
+		$gmt_offset = get_option('gmt_offset');
832
+		$prefix     = (int) $gmt_offset >= 0 ? '+' : '';
833
+		$parts      = explode('.', (string) $gmt_offset);
834
+		if (count($parts) === 1) {
835
+			$parts[1] = '00';
836
+		} else {
837
+			// convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838
+			// to minutes, eg 30 or 15, respectively
839
+			$hour_fraction = (float) ('0.' . $parts[1]);
840
+			$parts[1]      = (string) $hour_fraction * 60;
841
+		}
842
+		return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
843
+	}
844 844
 
845 845
 
846 846
 
847
-    /**
848
-     * So PHP does this awesome thing where if you are trying to get a timestamp
849
-     * for a month using a string like "February" or "February 2017",
850
-     * and you don't specify a day as part of your string,
851
-     * then PHP will use whatever the current day of the month is.
852
-     * IF the current day of the month happens to be the 30th or 31st,
853
-     * then PHP gets really confused by a date like February 30,
854
-     * so instead of saying
855
-     *      "Hey February only has 28 days (this year)...
856
-     *      ...you must have meant the last day of the month!"
857
-     * PHP does the next most logical thing, and bumps the date up to March 2nd,
858
-     * because someone requesting February 30th obviously meant March 1st!
859
-     * The way around this is to always set the day to the first,
860
-     * so that the month will stay on the month you wanted.
861
-     * this method will add that "1" into your date regardless of the format.
862
-     *
863
-     * @param string $month
864
-     * @return string
865
-     */
866
-    public static function first_of_month_timestamp($month = '')
867
-    {
868
-        $month = (string) $month;
869
-        $year  = '';
870
-        // check if the incoming string has a year in it or not
871
-        if (preg_match('/\b\d{4}\b/', $month, $matches)) {
872
-            $year = $matches[0];
873
-            // ten remove that from the month string as well as any spaces
874
-            $month = trim(str_replace($year, '', $month));
875
-            // add a space before the year
876
-            $year = " {$year}";
877
-        }
878
-        // return timestamp for something like "February 1 2017"
879
-        return strtotime("{$month} 1{$year}");
880
-    }
847
+	/**
848
+	 * So PHP does this awesome thing where if you are trying to get a timestamp
849
+	 * for a month using a string like "February" or "February 2017",
850
+	 * and you don't specify a day as part of your string,
851
+	 * then PHP will use whatever the current day of the month is.
852
+	 * IF the current day of the month happens to be the 30th or 31st,
853
+	 * then PHP gets really confused by a date like February 30,
854
+	 * so instead of saying
855
+	 *      "Hey February only has 28 days (this year)...
856
+	 *      ...you must have meant the last day of the month!"
857
+	 * PHP does the next most logical thing, and bumps the date up to March 2nd,
858
+	 * because someone requesting February 30th obviously meant March 1st!
859
+	 * The way around this is to always set the day to the first,
860
+	 * so that the month will stay on the month you wanted.
861
+	 * this method will add that "1" into your date regardless of the format.
862
+	 *
863
+	 * @param string $month
864
+	 * @return string
865
+	 */
866
+	public static function first_of_month_timestamp($month = '')
867
+	{
868
+		$month = (string) $month;
869
+		$year  = '';
870
+		// check if the incoming string has a year in it or not
871
+		if (preg_match('/\b\d{4}\b/', $month, $matches)) {
872
+			$year = $matches[0];
873
+			// ten remove that from the month string as well as any spaces
874
+			$month = trim(str_replace($year, '', $month));
875
+			// add a space before the year
876
+			$year = " {$year}";
877
+		}
878
+		// return timestamp for something like "February 1 2017"
879
+		return strtotime("{$month} 1{$year}");
880
+	}
881 881
 
882 882
 
883
-    /**
884
-     * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
885
-     * for this sites timezone, but the timestamp could be some other time GMT.
886
-     */
887
-    public static function tomorrow()
888
-    {
889
-        // The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
890
-        // before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
891
-        // not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
892
-        // final timestamp is equivalent to midnight in this timezone as represented in GMT.
893
-        return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
894
-    }
883
+	/**
884
+	 * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
885
+	 * for this sites timezone, but the timestamp could be some other time GMT.
886
+	 */
887
+	public static function tomorrow()
888
+	{
889
+		// The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
890
+		// before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
891
+		// not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
892
+		// final timestamp is equivalent to midnight in this timezone as represented in GMT.
893
+		return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
894
+	}
895 895
 
896 896
 
897
-    /**
898
-     * **
899
-     * Gives a nicely-formatted list of timezone strings.
900
-     * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
901
-     *
902
-     * @since     4.9.40.rc.008
903
-     * @staticvar bool $mo_loaded
904
-     * @staticvar string $locale_loaded
905
-     * @param string $selected_zone Selected timezone.
906
-     * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
907
-     * @return string
908
-     */
909
-    public static function wp_timezone_choice($selected_zone, $locale = null)
910
-    {
911
-        static $mo_loaded = false, $locale_loaded = null;
912
-        $continents = array(
913
-            'Africa',
914
-            'America',
915
-            'Antarctica',
916
-            'Arctic',
917
-            'Asia',
918
-            'Atlantic',
919
-            'Australia',
920
-            'Europe',
921
-            'Indian',
922
-            'Pacific',
923
-        );
924
-        // Load translations for continents and cities.
925
-        if (! $mo_loaded || $locale !== $locale_loaded) {
926
-            $locale_loaded = $locale ? $locale : get_locale();
927
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
928
-            unload_textdomain('continents-cities');
929
-            load_textdomain('continents-cities', $mofile);
930
-            $mo_loaded = true;
931
-        }
932
-        $zone_data = array();
933
-        foreach (timezone_identifiers_list() as $zone) {
934
-            $zone = explode('/', $zone);
935
-            if (! in_array($zone[0], $continents, true)) {
936
-                continue;
937
-            }
938
-            // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
-            $exists      = array(
940
-                0 => isset($zone[0]) && $zone[0],
941
-                1 => isset($zone[1]) && $zone[1],
942
-                2 => isset($zone[2]) && $zone[2],
943
-            );
944
-            $exists[3]   = $exists[0] && $zone[0] !== 'Etc';
945
-            $exists[4]   = $exists[1] && $exists[3];
946
-            $exists[5]   = $exists[2] && $exists[3];
947
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
948
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
949
-            // disabled because this code is copied from WordPress and is a WordPress domain
950
-            $zone_data[] = array(
951
-                'continent'   => $exists[0] ? $zone[0] : '',
952
-                'city'        => $exists[1] ? $zone[1] : '',
953
-                'subcity'     => $exists[2] ? $zone[2] : '',
954
-                't_continent' => $exists[3]
955
-                    ? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
956
-                    : '',
957
-                't_city'      => $exists[4]
958
-                    ? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
959
-                    : '',
960
-                't_subcity'   => $exists[5]
961
-                    ? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
962
-                    : '',
963
-            );
964
-            // phpcs:enable
965
-        }
966
-        usort($zone_data, '_wp_timezone_choice_usort_callback');
967
-        $structure = array();
968
-        if (empty($selected_zone)) {
969
-            $structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
970
-        }
971
-        foreach ($zone_data as $key => $zone) {
972
-            // Build value in an array to join later
973
-            $value = array($zone['continent']);
974
-            if (empty($zone['city'])) {
975
-                // It's at the continent level (generally won't happen)
976
-                $display = $zone['t_continent'];
977
-            } else {
978
-                // It's inside a continent group
979
-                // Continent optgroup
980
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
981
-                    $label       = $zone['t_continent'];
982
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
983
-                }
984
-                // Add the city to the value
985
-                $value[] = $zone['city'];
986
-                $display = $zone['t_city'];
987
-                if (! empty($zone['subcity'])) {
988
-                    // Add the subcity to the value
989
-                    $value[] = $zone['subcity'];
990
-                    $display .= ' - ' . $zone['t_subcity'];
991
-                }
992
-            }
993
-            // Build the value
994
-            $value       = implode('/', $value);
995
-            $selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
997
-                           . esc_html($display)
998
-                           . '</option>';
999
-            // Close continent optgroup
1000
-            if (! empty($zone['city'])
1001
-                && (
1002
-                    ! isset($zone_data[ $key + 1 ])
1003
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1004
-                )
1005
-            ) {
1006
-                $structure[] = '</optgroup>';
1007
-            }
1008
-        }
1009
-        return implode("\n", $structure);
1010
-    }
897
+	/**
898
+	 * **
899
+	 * Gives a nicely-formatted list of timezone strings.
900
+	 * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
901
+	 *
902
+	 * @since     4.9.40.rc.008
903
+	 * @staticvar bool $mo_loaded
904
+	 * @staticvar string $locale_loaded
905
+	 * @param string $selected_zone Selected timezone.
906
+	 * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
907
+	 * @return string
908
+	 */
909
+	public static function wp_timezone_choice($selected_zone, $locale = null)
910
+	{
911
+		static $mo_loaded = false, $locale_loaded = null;
912
+		$continents = array(
913
+			'Africa',
914
+			'America',
915
+			'Antarctica',
916
+			'Arctic',
917
+			'Asia',
918
+			'Atlantic',
919
+			'Australia',
920
+			'Europe',
921
+			'Indian',
922
+			'Pacific',
923
+		);
924
+		// Load translations for continents and cities.
925
+		if (! $mo_loaded || $locale !== $locale_loaded) {
926
+			$locale_loaded = $locale ? $locale : get_locale();
927
+			$mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
928
+			unload_textdomain('continents-cities');
929
+			load_textdomain('continents-cities', $mofile);
930
+			$mo_loaded = true;
931
+		}
932
+		$zone_data = array();
933
+		foreach (timezone_identifiers_list() as $zone) {
934
+			$zone = explode('/', $zone);
935
+			if (! in_array($zone[0], $continents, true)) {
936
+				continue;
937
+			}
938
+			// This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
+			$exists      = array(
940
+				0 => isset($zone[0]) && $zone[0],
941
+				1 => isset($zone[1]) && $zone[1],
942
+				2 => isset($zone[2]) && $zone[2],
943
+			);
944
+			$exists[3]   = $exists[0] && $zone[0] !== 'Etc';
945
+			$exists[4]   = $exists[1] && $exists[3];
946
+			$exists[5]   = $exists[2] && $exists[3];
947
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
948
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
949
+			// disabled because this code is copied from WordPress and is a WordPress domain
950
+			$zone_data[] = array(
951
+				'continent'   => $exists[0] ? $zone[0] : '',
952
+				'city'        => $exists[1] ? $zone[1] : '',
953
+				'subcity'     => $exists[2] ? $zone[2] : '',
954
+				't_continent' => $exists[3]
955
+					? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
956
+					: '',
957
+				't_city'      => $exists[4]
958
+					? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
959
+					: '',
960
+				't_subcity'   => $exists[5]
961
+					? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
962
+					: '',
963
+			);
964
+			// phpcs:enable
965
+		}
966
+		usort($zone_data, '_wp_timezone_choice_usort_callback');
967
+		$structure = array();
968
+		if (empty($selected_zone)) {
969
+			$structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
970
+		}
971
+		foreach ($zone_data as $key => $zone) {
972
+			// Build value in an array to join later
973
+			$value = array($zone['continent']);
974
+			if (empty($zone['city'])) {
975
+				// It's at the continent level (generally won't happen)
976
+				$display = $zone['t_continent'];
977
+			} else {
978
+				// It's inside a continent group
979
+				// Continent optgroup
980
+				if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
981
+					$label       = $zone['t_continent'];
982
+					$structure[] = '<optgroup label="' . esc_attr($label) . '">';
983
+				}
984
+				// Add the city to the value
985
+				$value[] = $zone['city'];
986
+				$display = $zone['t_city'];
987
+				if (! empty($zone['subcity'])) {
988
+					// Add the subcity to the value
989
+					$value[] = $zone['subcity'];
990
+					$display .= ' - ' . $zone['t_subcity'];
991
+				}
992
+			}
993
+			// Build the value
994
+			$value       = implode('/', $value);
995
+			$selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
+			$structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
997
+						   . esc_html($display)
998
+						   . '</option>';
999
+			// Close continent optgroup
1000
+			if (! empty($zone['city'])
1001
+				&& (
1002
+					! isset($zone_data[ $key + 1 ])
1003
+					|| (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1004
+				)
1005
+			) {
1006
+				$structure[] = '</optgroup>';
1007
+			}
1008
+		}
1009
+		return implode("\n", $structure);
1010
+	}
1011 1011
 
1012 1012
 
1013
-    /**
1014
-     * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1015
-     *
1016
-     * @param int|WP_User $user_id
1017
-     * @return string
1018
-     */
1019
-    public static function get_user_locale($user_id = 0)
1020
-    {
1021
-        if (function_exists('get_user_locale')) {
1022
-            return get_user_locale($user_id);
1023
-        }
1024
-        return get_locale();
1025
-    }
1013
+	/**
1014
+	 * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1015
+	 *
1016
+	 * @param int|WP_User $user_id
1017
+	 * @return string
1018
+	 */
1019
+	public static function get_user_locale($user_id = 0)
1020
+	{
1021
+		if (function_exists('get_user_locale')) {
1022
+			return get_user_locale($user_id);
1023
+		}
1024
+		return get_locale();
1025
+	}
1026 1026
 
1027 1027
 
1028
-    /**
1029
-     * Return the appropriate helper adapter for DTT related things.
1030
-     *
1031
-     * @return HelperInterface
1032
-     * @throws InvalidArgumentException
1033
-     * @throws InvalidDataTypeException
1034
-     * @throws InvalidInterfaceException
1035
-     */
1036
-    private static function getHelperAdapter()
1037
-    {
1038
-        $dtt_helper_fqcn = PHP_VERSION_ID < 50600
1039
-            ? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1040
-            : 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1041
-        return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1042
-    }
1028
+	/**
1029
+	 * Return the appropriate helper adapter for DTT related things.
1030
+	 *
1031
+	 * @return HelperInterface
1032
+	 * @throws InvalidArgumentException
1033
+	 * @throws InvalidDataTypeException
1034
+	 * @throws InvalidInterfaceException
1035
+	 */
1036
+	private static function getHelperAdapter()
1037
+	{
1038
+		$dtt_helper_fqcn = PHP_VERSION_ID < 50600
1039
+			? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1040
+			: 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1041
+		return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1042
+	}
1043 1043
 
1044 1044
 
1045
-    /**
1046
-     * Helper function for setting the timezone on a DateTime object.
1047
-     * This is implemented to standardize a workaround for a PHP bug outlined in
1048
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1049
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1050
-     *
1051
-     * @param DateTime     $datetime
1052
-     * @param DateTimeZone $timezone
1053
-     */
1054
-    public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1055
-    {
1056
-        $datetime->setTimezone($timezone);
1057
-        $datetime->getTimestamp();
1058
-    }
1045
+	/**
1046
+	 * Helper function for setting the timezone on a DateTime object.
1047
+	 * This is implemented to standardize a workaround for a PHP bug outlined in
1048
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1049
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1050
+	 *
1051
+	 * @param DateTime     $datetime
1052
+	 * @param DateTimeZone $timezone
1053
+	 */
1054
+	public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1055
+	{
1056
+		$datetime->setTimezone($timezone);
1057
+		$datetime->getTimestamp();
1058
+	}
1059 1059
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133 133
     {
134
-        $gmt_offset =  (int) $gmt_offset;
134
+        $gmt_offset = (int) $gmt_offset;
135 135
         /** @var array[] $abbreviations */
136 136
         $abbreviations = DateTimeZone::listAbbreviations();
137 137
         foreach ($abbreviations as $abbreviation) {
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
      */
327 327
     protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328 328
     {
329
-        if (! $DateTime instanceof DateTime) {
329
+        if ( ! $DateTime instanceof DateTime) {
330 330
             throw new EE_Error(
331 331
                 sprintf(
332 332
                     esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
@@ -336,25 +336,25 @@  discard block
 block discarded – undo
336 336
         }
337 337
         switch ($period) {
338 338
             case 'years':
339
-                $value = 'P' . $value . 'Y';
339
+                $value = 'P'.$value.'Y';
340 340
                 break;
341 341
             case 'months':
342
-                $value = 'P' . $value . 'M';
342
+                $value = 'P'.$value.'M';
343 343
                 break;
344 344
             case 'weeks':
345
-                $value = 'P' . $value . 'W';
345
+                $value = 'P'.$value.'W';
346 346
                 break;
347 347
             case 'days':
348
-                $value = 'P' . $value . 'D';
348
+                $value = 'P'.$value.'D';
349 349
                 break;
350 350
             case 'hours':
351
-                $value = 'PT' . $value . 'H';
351
+                $value = 'PT'.$value.'H';
352 352
                 break;
353 353
             case 'minutes':
354
-                $value = 'PT' . $value . 'M';
354
+                $value = 'PT'.$value.'M';
355 355
                 break;
356 356
             case 'seconds':
357
-                $value = 'PT' . $value . 'S';
357
+                $value = 'PT'.$value.'S';
358 358
                 break;
359 359
         }
360 360
         switch ($operand) {
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
      */
383 383
     protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384 384
     {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
385
+        if ( ! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386 386
             throw new EE_Error(
387 387
                 sprintf(
388 388
                     esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                 'date' => $date_format['js'],
496 496
                 'time' => $time_format['js'],
497 497
             ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
498
+            'moment' => $date_format['moment'].' '.$time_format['moment'],
499 499
             'moment_split' => array(
500 500
                 'date' => $date_format['moment'],
501 501
                 'time' => $time_format['moment']
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
          *
519 519
          * @var array
520 520
          */
521
-        $symbols_map          = array(
521
+        $symbols_map = array(
522 522
             // Day
523 523
             // 01
524 524
             'd' => array(
@@ -670,26 +670,26 @@  discard block
 block discarded – undo
670 670
         $escaping             = false;
671 671
         $format_string_length = strlen($format_string);
672 672
         for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
673
+            $char = $format_string[$i];
674 674
             if ($char === '\\') { // PHP date format escaping character
675 675
                 $i++;
676 676
                 if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
677
+                    $jquery_ui_format .= $format_string[$i];
678
+                    $moment_format    .= $format_string[$i];
679 679
                 } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
680
+                    $jquery_ui_format .= '\''.$format_string[$i];
681
+                    $moment_format    .= $format_string[$i];
682 682
                 }
683 683
                 $escaping = true;
684 684
             } else {
685 685
                 if ($escaping) {
686 686
                     $jquery_ui_format .= "'";
687 687
                     $moment_format    .= "'";
688
-                    $escaping         = false;
688
+                    $escaping = false;
689 689
                 }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
690
+                if (isset($symbols_map[$char])) {
691
+                    $jquery_ui_format .= $symbols_map[$char]['js'];
692
+                    $moment_format    .= $symbols_map[$char]['moment'];
693 693
                 } else {
694 694
                     $jquery_ui_format .= $char;
695 695
                     $moment_format    .= $char;
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
     public static function dates_represent_one_24_hour_date($date_1, $date_2)
747 747
     {
748 748
 
749
-        if ((! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
749
+        if (( ! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750 750
             || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
751 751
                 || $date_2->format(
752 752
                     EE_Datetime_Field::mysql_time_format
@@ -782,8 +782,8 @@  discard block
 block discarded – undo
782 782
             ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
783 783
             : (float) get_option('gmt_offset');
784 784
         $query_interval = $offset < 0
785
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
786
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
785
+            ? 'DATE_SUB('.$field_for_interval.', INTERVAL '.$offset * -1.' HOUR)'
786
+            : 'DATE_ADD('.$field_for_interval.', INTERVAL '.$offset.' HOUR)';
787 787
         return $query_interval;
788 788
     }
789 789
 
@@ -800,16 +800,16 @@  discard block
 block discarded – undo
800 800
     public static function get_timezone_string_for_display()
801 801
     {
802 802
         $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
803
-        if (! empty($pretty_timezone)) {
803
+        if ( ! empty($pretty_timezone)) {
804 804
             return esc_html($pretty_timezone);
805 805
         }
806 806
         $timezone_string = get_option('timezone_string');
807 807
         if ($timezone_string) {
808 808
             static $mo_loaded = false;
809 809
             // Load translations for continents and cities just like wp_timezone_choice does
810
-            if (! $mo_loaded) {
810
+            if ( ! $mo_loaded) {
811 811
                 $locale = get_locale();
812
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
812
+                $mofile = WP_LANG_DIR.'/continents-cities-'.$locale.'.mo';
813 813
                 load_textdomain('continents-cities', $mofile);
814 814
                 $mo_loaded = true;
815 815
             }
@@ -836,10 +836,10 @@  discard block
 block discarded – undo
836 836
         } else {
837 837
             // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
838 838
             // to minutes, eg 30 or 15, respectively
839
-            $hour_fraction = (float) ('0.' . $parts[1]);
839
+            $hour_fraction = (float) ('0.'.$parts[1]);
840 840
             $parts[1]      = (string) $hour_fraction * 60;
841 841
         }
842
-        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
842
+        return sprintf(__('UTC%1$s', 'event_espresso'), $prefix.implode(':', $parts));
843 843
     }
844 844
 
845 845
 
@@ -922,9 +922,9 @@  discard block
 block discarded – undo
922 922
             'Pacific',
923 923
         );
924 924
         // Load translations for continents and cities.
925
-        if (! $mo_loaded || $locale !== $locale_loaded) {
925
+        if ( ! $mo_loaded || $locale !== $locale_loaded) {
926 926
             $locale_loaded = $locale ? $locale : get_locale();
927
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
927
+            $mofile        = WP_LANG_DIR.'/continents-cities-'.$locale_loaded.'.mo';
928 928
             unload_textdomain('continents-cities');
929 929
             load_textdomain('continents-cities', $mofile);
930 930
             $mo_loaded = true;
@@ -932,11 +932,11 @@  discard block
 block discarded – undo
932 932
         $zone_data = array();
933 933
         foreach (timezone_identifiers_list() as $zone) {
934 934
             $zone = explode('/', $zone);
935
-            if (! in_array($zone[0], $continents, true)) {
935
+            if ( ! in_array($zone[0], $continents, true)) {
936 936
                 continue;
937 937
             }
938 938
             // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
939
-            $exists      = array(
939
+            $exists = array(
940 940
                 0 => isset($zone[0]) && $zone[0],
941 941
                 1 => isset($zone[1]) && $zone[1],
942 942
                 2 => isset($zone[2]) && $zone[2],
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
         usort($zone_data, '_wp_timezone_choice_usort_callback');
967 967
         $structure = array();
968 968
         if (empty($selected_zone)) {
969
-            $structure[] = '<option selected="selected" value="">' . __('Select a city', 'event_espresso') . '</option>';
969
+            $structure[] = '<option selected="selected" value="">'.__('Select a city', 'event_espresso').'</option>';
970 970
         }
971 971
         foreach ($zone_data as $key => $zone) {
972 972
             // Build value in an array to join later
@@ -977,30 +977,30 @@  discard block
 block discarded – undo
977 977
             } else {
978 978
                 // It's inside a continent group
979 979
                 // Continent optgroup
980
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
980
+                if ( ! isset($zone_data[$key - 1]) || $zone_data[$key - 1]['continent'] !== $zone['continent']) {
981 981
                     $label       = $zone['t_continent'];
982
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
982
+                    $structure[] = '<optgroup label="'.esc_attr($label).'">';
983 983
                 }
984 984
                 // Add the city to the value
985 985
                 $value[] = $zone['city'];
986 986
                 $display = $zone['t_city'];
987
-                if (! empty($zone['subcity'])) {
987
+                if ( ! empty($zone['subcity'])) {
988 988
                     // Add the subcity to the value
989 989
                     $value[] = $zone['subcity'];
990
-                    $display .= ' - ' . $zone['t_subcity'];
990
+                    $display .= ' - '.$zone['t_subcity'];
991 991
                 }
992 992
             }
993 993
             // Build the value
994 994
             $value       = implode('/', $value);
995 995
             $selected    = $value === $selected_zone ? ' selected="selected"' : '';
996
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
996
+            $structure[] = '<option value="'.esc_attr($value).'"'.$selected.'>'
997 997
                            . esc_html($display)
998 998
                            . '</option>';
999 999
             // Close continent optgroup
1000
-            if (! empty($zone['city'])
1000
+            if ( ! empty($zone['city'])
1001 1001
                 && (
1002
-                    ! isset($zone_data[ $key + 1 ])
1003
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1002
+                    ! isset($zone_data[$key + 1])
1003
+                    || (isset($zone_data[$key + 1]) && $zone_data[$key + 1]['continent'] !== $zone['continent'])
1004 1004
                 )
1005 1005
             ) {
1006 1006
                 $structure[] = '</optgroup>';
Please login to merge, or discard this patch.
core/services/helpers/datetime/HelperInterface.php 1 patch
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -16,94 +16,94 @@
 block discarded – undo
16 16
 interface HelperInterface
17 17
 {
18 18
 
19
-    /**
20
-     * Ensures that a valid timezone string is returned.
21
-     *
22
-     * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
-     *                                 settings (or derive from set UTC offset).
24
-     * @return string
25
-     */
26
-    public function getValidTimezoneString($timezone_string = '');
27
-
28
-
29
-    /**
30
-     * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
31
-     *
32
-     * @param string $timezone_string
33
-     * @param bool   $throw_error
34
-     * @return bool
35
-     */
36
-    public function validateTimezone($timezone_string, $throw_error = true);
37
-
38
-
39
-    /**
40
-     * Returns a timezone string for the provided gmt_offset.
41
-     * @param float|string $gmt_offset
42
-     * @return string
43
-     */
44
-    public function getTimezoneStringFromGmtOffset($gmt_offset = '');
45
-
46
-
47
-    /**
48
-     * Gets the site's GMT offset based on either the timezone string
49
-     * (in which case the gmt offset will vary depending on the location's
50
-     * observance of daylight savings time) or the gmt_offset wp option
51
-     *
52
-     * @return int  seconds offset
53
-     */
54
-    public function getSiteTimezoneGmtOffset();
55
-
56
-
57
-    /**
58
-     * Get timezone transitions
59
-     * @param DateTimeZone $date_time_zone
60
-     * @param int|null     $time
61
-     * @param bool         $first_only
62
-     * @return array
63
-     */
64
-    public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
65
-
66
-
67
-    /**
68
-     * Get Timezone offset for given timezone object
69
-     * @param DateTimeZone $date_time_zone
70
-     * @param null|int         $time
71
-     * @return int
72
-     */
73
-    public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
74
-
75
-
76
-    /**
77
-     * Provide a timezone select input
78
-     * @param string $timezone_string
79
-     * @return string
80
-     */
81
-    public function timezoneSelectInput($timezone_string = '');
82
-
83
-
84
-    /**
85
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
86
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
87
-     * the site is used.
88
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
89
-     * computed timestamp (i.e. date_i18n() )
90
-     *
91
-     * @param int    $unix_timestamp    if 0, then time() will be used.
92
-     * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
93
-     *                                site will be used.
94
-     * @return int      unix_timestamp value with the offset applied for the given timezone.
95
-     */
96
-    public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
97
-
98
-
99
-    /**
100
-     * Depending on PHP version,
101
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
103
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
-     *
105
-     * @param int $gmt_offset
106
-     * @return int
107
-     */
108
-    public function adjustInvalidGmtOffsets($gmt_offset);
19
+	/**
20
+	 * Ensures that a valid timezone string is returned.
21
+	 *
22
+	 * @param string $timezone_string  When not provided then attempt to use the timezone_string set in the WP Time
23
+	 *                                 settings (or derive from set UTC offset).
24
+	 * @return string
25
+	 */
26
+	public function getValidTimezoneString($timezone_string = '');
27
+
28
+
29
+	/**
30
+	 * The only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
31
+	 *
32
+	 * @param string $timezone_string
33
+	 * @param bool   $throw_error
34
+	 * @return bool
35
+	 */
36
+	public function validateTimezone($timezone_string, $throw_error = true);
37
+
38
+
39
+	/**
40
+	 * Returns a timezone string for the provided gmt_offset.
41
+	 * @param float|string $gmt_offset
42
+	 * @return string
43
+	 */
44
+	public function getTimezoneStringFromGmtOffset($gmt_offset = '');
45
+
46
+
47
+	/**
48
+	 * Gets the site's GMT offset based on either the timezone string
49
+	 * (in which case the gmt offset will vary depending on the location's
50
+	 * observance of daylight savings time) or the gmt_offset wp option
51
+	 *
52
+	 * @return int  seconds offset
53
+	 */
54
+	public function getSiteTimezoneGmtOffset();
55
+
56
+
57
+	/**
58
+	 * Get timezone transitions
59
+	 * @param DateTimeZone $date_time_zone
60
+	 * @param int|null     $time
61
+	 * @param bool         $first_only
62
+	 * @return array
63
+	 */
64
+	public function getTimezoneTransitions(DateTimeZone $date_time_zone, $time = null, $first_only = true);
65
+
66
+
67
+	/**
68
+	 * Get Timezone offset for given timezone object
69
+	 * @param DateTimeZone $date_time_zone
70
+	 * @param null|int         $time
71
+	 * @return int
72
+	 */
73
+	public function getTimezoneOffset(DateTimeZone $date_time_zone, $time = null);
74
+
75
+
76
+	/**
77
+	 * Provide a timezone select input
78
+	 * @param string $timezone_string
79
+	 * @return string
80
+	 */
81
+	public function timezoneSelectInput($timezone_string = '');
82
+
83
+
84
+	/**
85
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
86
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
87
+	 * the site is used.
88
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
89
+	 * computed timestamp (i.e. date_i18n() )
90
+	 *
91
+	 * @param int    $unix_timestamp    if 0, then time() will be used.
92
+	 * @param string $timezone_string timezone_string. If empty, then the current set timezone for the
93
+	 *                                site will be used.
94
+	 * @return int      unix_timestamp value with the offset applied for the given timezone.
95
+	 */
96
+	public function getTimestampWithOffset($unix_timestamp = 0, $timezone_string = '');
97
+
98
+
99
+	/**
100
+	 * Depending on PHP version,
101
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
103
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
+	 *
105
+	 * @param int $gmt_offset
106
+	 * @return int
107
+	 */
108
+	public function adjustInvalidGmtOffsets($gmt_offset);
109 109
 }
Please login to merge, or discard this patch.
core/services/context/ContextChecker.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@
 block discarded – undo
87 87
     {
88 88
         $this->evaluation_callback = $evaluation_callback instanceof Closure
89 89
             ? $evaluation_callback
90
-            : function (ContextInterface $context, $acceptable_values) {
90
+            : function(ContextInterface $context, $acceptable_values) {
91 91
                 return in_array($context->slug(), $acceptable_values, true);
92 92
             };
93 93
     }
Please login to merge, or discard this patch.
Indentation   +141 added lines, -141 removed lines patch added patch discarded remove patch
@@ -17,145 +17,145 @@
 block discarded – undo
17 17
 class ContextChecker
18 18
 {
19 19
 
20
-    /**
21
-     * A unique string used to identify where this ContextChecker is being employed
22
-     * Is currently only used within the hook name for the filterable return value of isAllowed().
23
-     *
24
-     * @var string $identifier
25
-     */
26
-    private $identifier;
27
-
28
-    /**
29
-     * A list of values to be compared against the slug of the Context class passed to isAllowed()
30
-     *
31
-     * @var array $acceptable_values
32
-     */
33
-    private $acceptable_values;
34
-
35
-    /**
36
-     * Closure that will be called to perform the evaluation within isAllowed().
37
-     * If none is provided, then a simple type sensitive in_array() check will be used
38
-     * and return true if the incoming Context::slug() is found within the array of $acceptable_values.
39
-     *
40
-     * @var Closure $evaluation_callback
41
-     */
42
-    private $evaluation_callback;
43
-
44
-
45
-    /**
46
-     * ContextChecker constructor.
47
-     *
48
-     * @param string       $identifier
49
-     * @param array        $acceptable_values
50
-     * @param Closure|null $evaluation_callback [optional]
51
-     */
52
-    public function __construct($identifier, array $acceptable_values, Closure $evaluation_callback = null)
53
-    {
54
-        $this->setIdentifier($identifier);
55
-        $this->setAcceptableValues($acceptable_values);
56
-        $this->setEvaluationCallback($evaluation_callback);
57
-    }
58
-
59
-
60
-    /**
61
-     * @param string $identifier
62
-     */
63
-    private function setIdentifier($identifier)
64
-    {
65
-        $this->identifier = sanitize_key($identifier);
66
-    }
67
-
68
-
69
-    /**
70
-     * @param array $acceptable_values
71
-     */
72
-    private function setAcceptableValues(array $acceptable_values)
73
-    {
74
-        $this->acceptable_values = $acceptable_values;
75
-    }
76
-
77
-
78
-    /**
79
-     * @param Closure $evaluation_callback
80
-     */
81
-    private function setEvaluationCallback(Closure $evaluation_callback = null)
82
-    {
83
-        $this->evaluation_callback = $evaluation_callback instanceof Closure
84
-            ? $evaluation_callback
85
-            : function (ContextInterface $context, $acceptable_values) {
86
-                return in_array($context->slug(), $acceptable_values, true);
87
-            };
88
-    }
89
-
90
-
91
-    /**
92
-     * @return string
93
-     */
94
-    protected function identifier()
95
-    {
96
-        return $this->identifier;
97
-    }
98
-
99
-
100
-    /**
101
-     * @return array
102
-     */
103
-    protected function acceptableValues()
104
-    {
105
-        return apply_filters(
106
-            "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__acceptableValues",
107
-            $this->acceptable_values
108
-        );
109
-    }
110
-
111
-
112
-    /**
113
-     * @return Closure
114
-     */
115
-    protected function evaluationCallback()
116
-    {
117
-        return $this->evaluation_callback;
118
-    }
119
-
120
-
121
-    /**
122
-     * Returns true if the incoming Context class slug matches one of the preset acceptable values.
123
-     * The result is filterable using the identifier for this ContextChecker.
124
-     * example:
125
-     * If this ContextChecker's $identifier was set to "registration-checkout-type",
126
-     * then the filter here would be named:
127
-     *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed".
128
-     * Other code could hook into the filter in isAllowed() using the above name
129
-     * and test for additional acceptable values.
130
-     * So if the set of $acceptable_values was: [ "initial-visit",  "revisit" ]
131
-     * then adding a filter to
132
-     *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed",
133
-     * would allow you to perform your own conditional and allow "wait-list-checkout" as an acceptable value.
134
-     *  example:
135
-     *      add_filter(
136
-     *          'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed',
137
-     *          function ($is_allowed, ContextInterface $context) { return $context->slug() === 'wait-list-checkout'
138
-     *                  ? true
139
-     *                  : $is_allowed;
140
-     *          },
141
-     *          10,
142
-     *          2
143
-     *      );
144
-     *
145
-     * @param ContextInterface $context
146
-     * @return boolean
147
-     */
148
-    public function isAllowed(ContextInterface $context)
149
-    {
150
-        $evaluation_callback = $this->evaluationCallback();
151
-        return filter_var(
152
-            apply_filters(
153
-                "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__isAllowed",
154
-                $evaluation_callback($context, $this->acceptableValues()),
155
-                $context,
156
-                $this
157
-            ),
158
-            FILTER_VALIDATE_BOOLEAN
159
-        );
160
-    }
20
+	/**
21
+	 * A unique string used to identify where this ContextChecker is being employed
22
+	 * Is currently only used within the hook name for the filterable return value of isAllowed().
23
+	 *
24
+	 * @var string $identifier
25
+	 */
26
+	private $identifier;
27
+
28
+	/**
29
+	 * A list of values to be compared against the slug of the Context class passed to isAllowed()
30
+	 *
31
+	 * @var array $acceptable_values
32
+	 */
33
+	private $acceptable_values;
34
+
35
+	/**
36
+	 * Closure that will be called to perform the evaluation within isAllowed().
37
+	 * If none is provided, then a simple type sensitive in_array() check will be used
38
+	 * and return true if the incoming Context::slug() is found within the array of $acceptable_values.
39
+	 *
40
+	 * @var Closure $evaluation_callback
41
+	 */
42
+	private $evaluation_callback;
43
+
44
+
45
+	/**
46
+	 * ContextChecker constructor.
47
+	 *
48
+	 * @param string       $identifier
49
+	 * @param array        $acceptable_values
50
+	 * @param Closure|null $evaluation_callback [optional]
51
+	 */
52
+	public function __construct($identifier, array $acceptable_values, Closure $evaluation_callback = null)
53
+	{
54
+		$this->setIdentifier($identifier);
55
+		$this->setAcceptableValues($acceptable_values);
56
+		$this->setEvaluationCallback($evaluation_callback);
57
+	}
58
+
59
+
60
+	/**
61
+	 * @param string $identifier
62
+	 */
63
+	private function setIdentifier($identifier)
64
+	{
65
+		$this->identifier = sanitize_key($identifier);
66
+	}
67
+
68
+
69
+	/**
70
+	 * @param array $acceptable_values
71
+	 */
72
+	private function setAcceptableValues(array $acceptable_values)
73
+	{
74
+		$this->acceptable_values = $acceptable_values;
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param Closure $evaluation_callback
80
+	 */
81
+	private function setEvaluationCallback(Closure $evaluation_callback = null)
82
+	{
83
+		$this->evaluation_callback = $evaluation_callback instanceof Closure
84
+			? $evaluation_callback
85
+			: function (ContextInterface $context, $acceptable_values) {
86
+				return in_array($context->slug(), $acceptable_values, true);
87
+			};
88
+	}
89
+
90
+
91
+	/**
92
+	 * @return string
93
+	 */
94
+	protected function identifier()
95
+	{
96
+		return $this->identifier;
97
+	}
98
+
99
+
100
+	/**
101
+	 * @return array
102
+	 */
103
+	protected function acceptableValues()
104
+	{
105
+		return apply_filters(
106
+			"FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__acceptableValues",
107
+			$this->acceptable_values
108
+		);
109
+	}
110
+
111
+
112
+	/**
113
+	 * @return Closure
114
+	 */
115
+	protected function evaluationCallback()
116
+	{
117
+		return $this->evaluation_callback;
118
+	}
119
+
120
+
121
+	/**
122
+	 * Returns true if the incoming Context class slug matches one of the preset acceptable values.
123
+	 * The result is filterable using the identifier for this ContextChecker.
124
+	 * example:
125
+	 * If this ContextChecker's $identifier was set to "registration-checkout-type",
126
+	 * then the filter here would be named:
127
+	 *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed".
128
+	 * Other code could hook into the filter in isAllowed() using the above name
129
+	 * and test for additional acceptable values.
130
+	 * So if the set of $acceptable_values was: [ "initial-visit",  "revisit" ]
131
+	 * then adding a filter to
132
+	 *  "FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed",
133
+	 * would allow you to perform your own conditional and allow "wait-list-checkout" as an acceptable value.
134
+	 *  example:
135
+	 *      add_filter(
136
+	 *          'FHEE__EventEspresso_core_domain_entities_context_ContextChecker__registration-checkout-type__isAllowed',
137
+	 *          function ($is_allowed, ContextInterface $context) { return $context->slug() === 'wait-list-checkout'
138
+	 *                  ? true
139
+	 *                  : $is_allowed;
140
+	 *          },
141
+	 *          10,
142
+	 *          2
143
+	 *      );
144
+	 *
145
+	 * @param ContextInterface $context
146
+	 * @return boolean
147
+	 */
148
+	public function isAllowed(ContextInterface $context)
149
+	{
150
+		$evaluation_callback = $this->evaluationCallback();
151
+		return filter_var(
152
+			apply_filters(
153
+				"FHEE__EventEspresso_core_domain_entities_context_ContextChecker__{$this->identifier}__isAllowed",
154
+				$evaluation_callback($context, $this->acceptableValues()),
155
+				$context,
156
+				$this
157
+			),
158
+			FILTER_VALIDATE_BOOLEAN
159
+		);
160
+	}
161 161
 }
Please login to merge, or discard this patch.
core/domain/entities/contexts/ContextInterface.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -18,14 +18,14 @@
 block discarded – undo
18 18
 interface ContextInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @return string
23
-     */
24
-    public function slug();
21
+	/**
22
+	 * @return string
23
+	 */
24
+	public function slug();
25 25
 
26 26
 
27
-    /**
28
-     * @return string
29
-     */
30
-    public function description();
27
+	/**
28
+	 * @return string
29
+	 */
30
+	public function description();
31 31
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Question.model.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
      * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
365 365
      * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
366 366
      * @param $QST_system
367
-     * @return int of QST_ID for the question that corresponds to that QST_system
367
+     * @return string of QST_ID for the question that corresponds to that QST_system
368 368
      */
369 369
     public function get_Question_ID_from_system_string($QST_system)
370 370
     {
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 
426 426
 
427 427
     /**
428
-     * @return array
428
+     * @return EEM_Question
429 429
      */
430 430
     public function question_descriptions()
431 431
     {
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -213,10 +213,10 @@  discard block
 block discarded – undo
213 213
             'Question_Group_Question' => new EE_Has_Many_Relation()
214 214
         );
215 215
         // this model is generally available for reading
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
217
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
216
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
217
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Reg_Form('QST_system');
220 220
         parent::__construct($timezone);
221 221
     }
222 222
 
@@ -256,10 +256,10 @@  discard block
 block discarded – undo
256 256
      */
257 257
     public function question_type_is_in_category($question_type, $category)
258 258
     {
259
-        if (!isset($this->_question_type_categories[ $category ])) {
259
+        if ( ! isset($this->_question_type_categories[$category])) {
260 260
             return false;
261 261
         }
262
-        return in_array($question_type, $this->_question_type_categories[ $category ]);
262
+        return in_array($question_type, $this->_question_type_categories[$category]);
263 263
     }
264 264
 
265 265
 
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
      */
271 271
     public function question_types_in_category($category)
272 272
     {
273
-        if (isset($this->_question_type_categories[ $category ])) {
274
-            return $this->_question_type_categories[ $category ];
273
+        if (isset($this->_question_type_categories[$category])) {
274
+            return $this->_question_type_categories[$category];
275 275
         }
276 276
         return array();
277 277
     }
@@ -410,8 +410,8 @@  discard block
 block discarded – undo
410 410
     public function absolute_max_for_system_question($system_question_value)
411 411
     {
412 412
         $maxes = $this->system_question_maxes();
413
-        if (isset($maxes[ $system_question_value ])) {
414
-            return $maxes[ $system_question_value ];
413
+        if (isset($maxes[$system_question_value])) {
414
+            return $maxes[$system_question_value];
415 415
         } else {
416 416
             return EE_INF;
417 417
         }
Please login to merge, or discard this patch.
Indentation   +425 added lines, -425 removed lines patch added patch discarded remove patch
@@ -10,429 +10,429 @@
 block discarded – undo
10 10
 class EEM_Question extends EEM_Soft_Delete_Base
11 11
 {
12 12
 
13
-    // constant used to indicate that the question type is COUNTRY
14
-    const QST_type_country = 'COUNTRY';
15
-
16
-    // constant used to indicate that the question type is DATE
17
-    const QST_type_date = 'DATE';
18
-
19
-    // constant used to indicate that the question type is DROPDOWN
20
-    const QST_type_dropdown = 'DROPDOWN';
21
-
22
-    // constant used to indicate that the question type is CHECKBOX
23
-    const QST_type_checkbox = 'CHECKBOX';
24
-
25
-    // constant used to indicate that the question type is RADIO_BTN
26
-    const QST_type_radio = 'RADIO_BTN';
27
-
28
-    // constant used to indicate that the question type is STATE
29
-    const QST_type_state = 'STATE';
30
-
31
-    // constant used to indicate that the question type is TEXT
32
-    const QST_type_text = 'TEXT';
33
-
34
-    // constant used to indicate that the question type is TEXTAREA
35
-    const QST_type_textarea = 'TEXTAREA';
36
-
37
-    // constant used to indicate that the question type is a TEXTAREA that allows simple html
38
-    const QST_type_html_textarea = 'HTML_TEXTAREA';
39
-
40
-    // constant used to indicate that the question type is an email input
41
-    const QST_type_email = 'EMAIL';
42
-
43
-    // constant used to indicate that the question type is a US-formatted phone number
44
-    const QST_type_us_phone = 'US_PHONE';
45
-
46
-    // constant used to indicate that the question type is an integer (whole number)
47
-    const QST_type_int = 'INTEGER';
48
-
49
-    // constant used to indicate that the question type is a decimal (float)
50
-    const QST_type_decimal = 'DECIMAL';
51
-
52
-    // constant used to indicate that the question type is a valid URL
53
-    const QST_type_url = 'URL';
54
-
55
-    // constant used to indicate that the question type is a YEAR
56
-    const QST_type_year = 'YEAR';
57
-
58
-    // constant used to indicate that the question type is a multi-select
59
-    const QST_type_multi_select = 'MULTI_SELECT';
60
-
61
-    /**
62
-     * Question types that are interchangeable, even after answers have been provided for them.
63
-     * Top-level keys are category slugs, next level is an array of question types. If question types
64
-     * aren't in this array, it is assumed they AREN'T interchangeable with any other question types.
65
-     *
66
-     * @access protected
67
-     * @var array $_question_type_categories {
68
-     * @type string $text
69
-     * @type string $single -answer-enum
70
-     * @type string $multi -answer-enum
71
-     *                    }
72
-     */
73
-    protected $_question_type_categories = array();
74
-
75
-    /**
76
-     * lists all the question types which should be allowed. Ideally, this will be extensible.
77
-     *
78
-     * @access protected
79
-     * @var array $_allowed_question_types
80
-     */
81
-    protected $_allowed_question_types = array();
82
-
83
-    /**
84
-     * brief descriptions for all the question types
85
-     *
86
-     * @access protected
87
-     * @var EEM_Question $_instance
88
-     */
89
-    protected $_question_descriptions;
90
-
91
-
92
-    /**
93
-     * Question types that should have an admin-defined max input length
94
-     * @var array
95
-     */
96
-    protected $question_types_with_max_lengh;
97
-
98
-
99
-    // private instance of the Attendee object
100
-    protected static $_instance = null;
101
-
102
-
103
-    /**
104
-     * EEM_Question constructor.
105
-     *
106
-     * @param null $timezone
107
-     */
108
-    protected function __construct($timezone = null)
109
-    {
110
-        $this->singular_item = __('Question', 'event_espresso');
111
-        $this->plural_item = __('Questions', 'event_espresso');
112
-        $this->_allowed_question_types = apply_filters(
113
-            'FHEE__EEM_Question__construct__allowed_question_types',
114
-            array(
115
-                EEM_Question::QST_type_text => __('Text', 'event_espresso'),
116
-                EEM_Question::QST_type_textarea => __('Textarea', 'event_espresso'),
117
-                EEM_Question::QST_type_checkbox => __('Checkboxes', 'event_espresso'),
118
-                EEM_Question::QST_type_radio => __('Radio Buttons', 'event_espresso'),
119
-                EEM_Question::QST_type_dropdown => __('Dropdown', 'event_espresso'),
120
-                EEM_Question::QST_type_state => __('State/Province Dropdown', 'event_espresso'),
121
-                EEM_Question::QST_type_country => __('Country Dropdown', 'event_espresso'),
122
-                EEM_Question::QST_type_date => __('Date Picker', 'event_espresso'),
123
-                EEM_Question::QST_type_html_textarea => __('HTML Textarea', 'event_espresso'),
124
-                EEM_Question::QST_type_email => __('Email', 'event_espresso'),
125
-                EEM_Question::QST_type_us_phone => __('USA - Format Phone', 'event_espresso'),
126
-                EEM_Question::QST_type_decimal => __('Number', 'event_espresso'),
127
-                EEM_Question::QST_type_int => __('Whole Number', 'event_espresso'),
128
-                EEM_Question::QST_type_url => __('URL', 'event_espresso'),
129
-                EEM_Question::QST_type_year => __('Year', 'event_espresso'),
130
-                EEM_Question::QST_type_multi_select => __('Multi Select', 'event_espresso')
131
-            )
132
-        );
133
-        $this->_question_descriptions = apply_filters(
134
-            'FHEE__EEM_Question__construct__question_descriptions',
135
-            array(
136
-                EEM_Question::QST_type_text => __('A single line text input field', 'event_espresso'),
137
-                EEM_Question::QST_type_textarea => __('A multi line text input field', 'event_espresso'),
138
-                EEM_Question::QST_type_checkbox => __('Allows multiple preset options to be selected', 'event_espresso'),
139
-                EEM_Question::QST_type_radio => __('Allows a single preset option to be selected', 'event_espresso'),
140
-                EEM_Question::QST_type_dropdown => __('A dropdown that allows a single selection', 'event_espresso'),
141
-                EEM_Question::QST_type_state => __('A dropdown that lists states/provinces', 'event_espresso'),
142
-                EEM_Question::QST_type_country => __('A dropdown that lists countries', 'event_espresso'),
143
-                EEM_Question::QST_type_date => __('A popup calendar that allows date selections', 'event_espresso'),
144
-                EEM_Question::QST_type_html_textarea => __('A multi line text input field that allows HTML', 'event_espresso'),
145
-                EEM_Question::QST_type_email => __('A text field that must contain a valid Email address', 'event_espresso'),
146
-                EEM_Question::QST_type_us_phone => __('A text field that must contain a valid US phone number', 'event_espresso'),
147
-                EEM_Question::QST_type_decimal => __('A text field that allows number values with decimals', 'event_espresso'),
148
-                EEM_Question::QST_type_int => __('A text field that only allows whole numbers (no decimals)', 'event_espresso'),
149
-                EEM_Question::QST_type_url => __('A text field that must contain a valid URL', 'event_espresso'),
150
-                EEM_Question::QST_type_year => __('A dropdown that lists the last 100 years', 'event_espresso'),
151
-                EEM_Question::QST_type_multi_select => __('A dropdown that allows multiple selections', 'event_espresso')
152
-            )
153
-        );
154
-        $this->_question_type_categories = (array) apply_filters(
155
-            'FHEE__EEM_Question__construct__question_type_categories',
156
-            array(
157
-                'text' => array(
158
-                    EEM_Question::QST_type_text,
159
-                    EEM_Question::QST_type_textarea,
160
-                    EEM_Question::QST_type_date,
161
-                    EEM_Question::QST_type_html_textarea,
162
-                    EEM_Question::QST_type_email,
163
-                    EEM_Question::QST_type_us_phone,
164
-                    EEM_Question::QST_type_decimal,
165
-                    EEM_Question::QST_type_int,
166
-                    EEM_Question::QST_type_url,
167
-                    EEM_Question::QST_type_year
168
-                ),
169
-                'single-answer-enum' => array(
170
-                    EEM_Question::QST_type_radio,
171
-                    EEM_Question::QST_type_dropdown
172
-                ),
173
-                'multi-answer-enum' => array(
174
-                    EEM_Question::QST_type_checkbox,
175
-                    EEM_Question::QST_type_multi_select
176
-                )
177
-            )
178
-        );
179
-        $this->question_types_with_max_lengh = apply_filters(
180
-            'FHEE__EEM_Question___construct__question_types_with_max_length',
181
-            array(
182
-                EEM_Question::QST_type_text,
183
-                EEM_Question::QST_type_textarea,
184
-                EEM_Question::QST_type_html_textarea
185
-            )
186
-        );
187
-
188
-        $this->_tables = array(
189
-            'Question' => new EE_Primary_Table('esp_question', 'QST_ID')
190
-        );
191
-        $this->_fields = array(
192
-            'Question' => array(
193
-                'QST_ID' => new EE_Primary_Key_Int_Field('QST_ID', __('Question ID', 'event_espresso')),
194
-                'QST_display_text' => new EE_Post_Content_Field('QST_display_text', __('Question Text', 'event_espresso'), true, ''),
195
-                'QST_admin_label' => new EE_Plain_Text_Field('QST_admin_label', __('Question Label (admin-only)', 'event_espresso'), true, ''),
196
-                'QST_system' => new EE_Plain_Text_Field('QST_system', __('Internal string ID for question', 'event_espresso'), false, ''),
197
-                'QST_type' => new EE_Enum_Text_Field('QST_type', __('Question Type', 'event_espresso'), false, 'TEXT', $this->_allowed_question_types),
198
-                'QST_required' => new EE_Boolean_Field('QST_required', __('Required Question?', 'event_espresso'), false, false),
199
-                'QST_required_text' => new EE_Simple_HTML_Field('QST_required_text', __('Text to Display if Not Provided', 'event_espresso'), true, ''),
200
-                'QST_order' => new EE_Integer_Field('QST_order', __('Question Order', 'event_espresso'), false, 0),
201
-                'QST_admin_only' => new EE_Boolean_Field('QST_admin_only', __('Admin-Only Question?', 'event_espresso'), false, false),
202
-                'QST_max' => new EE_Infinite_Integer_Field('QST_max', __('Max Size', 'event_espresso'), false, EE_INF),
203
-                'QST_wp_user' => new EE_WP_User_Field('QST_wp_user', __('Question Creator ID', 'event_espresso'), false),
204
-                'QST_deleted' => new EE_Trashed_Flag_Field('QST_deleted', __('Flag Indicating question was deleted', 'event_espresso'), false, false)
205
-            )
206
-        );
207
-        $this->_model_relations = array(
208
-            'Question_Group' => new EE_HABTM_Relation('Question_Group_Question'),
209
-            'Question_Option' => new EE_Has_Many_Relation(),
210
-            'Answer' => new EE_Has_Many_Relation(),
211
-            'WP_User' => new EE_Belongs_To_Relation(),
212
-            // for QST_order column
213
-            'Question_Group_Question' => new EE_Has_Many_Relation()
214
-        );
215
-        // this model is generally available for reading
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
217
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
220
-        parent::__construct($timezone);
221
-    }
222
-
223
-    /**
224
-     * Returns the list of allowed question types, which are normally: 'TEXT','TEXTAREA','RADIO_BTN','DROPDOWN','CHECKBOX','DATE'
225
-     * but they can be extended
226
-     * @return string[]
227
-     */
228
-    public function allowed_question_types()
229
-    {
230
-        return $this->_allowed_question_types;
231
-    }
232
-
233
-    /**
234
-     * Gets all the question types in the same category
235
-     * @param string $question_type one of EEM_Question::allowed_question_types(
236
-     * @return string[] like EEM_Question::allowed_question_types()
237
-     */
238
-    public function question_types_in_same_category($question_type)
239
-    {
240
-        $question_types = array($question_type);
241
-        foreach ($this->_question_type_categories as $category => $question_types_in_category) {
242
-            if (in_array($question_type, $question_types_in_category)) {
243
-                $question_types = $question_types_in_category;
244
-                break;
245
-            }
246
-        }
247
-
248
-        return array_intersect_key($this->allowed_question_types(), array_flip($question_types));
249
-    }
250
-
251
-    /**
252
-     * Determines if the given question type is in the given question type category
253
-     * @param string $question_type one of EEM_Question::allowed_question_types()
254
-     * @param string $category one of the top-level keys of EEM_Question::question_type_categories()
255
-     * @return boolean
256
-     */
257
-    public function question_type_is_in_category($question_type, $category)
258
-    {
259
-        if (!isset($this->_question_type_categories[ $category ])) {
260
-            return false;
261
-        }
262
-        return in_array($question_type, $this->_question_type_categories[ $category ]);
263
-    }
264
-
265
-
266
-    /**
267
-     * Returns all the question types in the given category
268
-     * @param string $category
269
-     * @return array|mixed
270
-     */
271
-    public function question_types_in_category($category)
272
-    {
273
-        if (isset($this->_question_type_categories[ $category ])) {
274
-            return $this->_question_type_categories[ $category ];
275
-        }
276
-        return array();
277
-    }
278
-
279
-
280
-    /**
281
-     * Returns all the question types that should have question options
282
-     * @return array
283
-     */
284
-    public function question_types_with_options()
285
-    {
286
-        return array_merge(
287
-            $this->question_types_in_category('single-answer-enum'),
288
-            $this->question_types_in_category('multi-answer-enum')
289
-        );
290
-    }
291
-
292
-    /**
293
-     * Returns the question type categories 2d array
294
-     * @return array see EEM_Question::_question_type_categories
295
-     */
296
-    public function question_type_categories()
297
-    {
298
-        return $this->_question_type_categories;
299
-    }
300
-
301
-    /**
302
-     * Returns an array of all the QST_system values that can be allowed in the system question group
303
-     * identified by $system_question_group_id
304
-     * @param string $system_question_group_id QSG_system
305
-     * @return array of system question names (QST_system)
306
-     */
307
-    public function allowed_system_questions_in_system_question_group($system_question_group_id)
308
-    {
309
-        $question_system_ids = array();
310
-        switch ($system_question_group_id) {
311
-            case EEM_Question_Group::system_personal:
312
-                $question_system_ids = array(
313
-                    EEM_Attendee::system_question_fname,
314
-                    EEM_Attendee::system_question_lname,
315
-                    EEM_Attendee::system_question_email,
316
-                    EEM_Attendee::system_question_phone
317
-                );
318
-                break;
319
-            case EEM_Question_Group::system_address:
320
-                $question_system_ids = array(
321
-                    EEM_Attendee::system_question_address,
322
-                    EEM_Attendee::system_question_address2,
323
-                    EEM_Attendee::system_question_city,
324
-                    EEM_Attendee::system_question_state,
325
-                    EEM_Attendee::system_question_country,
326
-                    EEM_Attendee::system_question_zip,
327
-                    EEM_Attendee::system_question_phone
328
-                );
329
-                break;
330
-        }
331
-        return apply_filters('FHEE__EEM_Question__system_questions_allowed_in_system_question_group__return', $question_system_ids, $system_question_group_id);
332
-    }
333
-
334
-    /**
335
-     * Returns an array of all the QST_system values that are required in the system question group
336
-     * identified by $system_question_group_id
337
-     * @param string $system_question_group_id QSG_system
338
-     * @return array of system question names (QST_system)
339
-     */
340
-    public function required_system_questions_in_system_question_group($system_question_group_id)
341
-    {
342
-        $question_system_ids = null;
343
-        switch ($system_question_group_id) {
344
-            case EEM_Question_Group::system_personal:
345
-                $question_system_ids = array(
346
-                    EEM_Attendee::system_question_fname,
347
-                    EEM_Attendee::system_question_email,
348
-                );
349
-                break;
350
-            default:
351
-                $question_system_ids = array();
352
-        }
353
-        return apply_filters('FHEE__EEM_Question__system_questions_required_in_system_question_group', $question_system_ids, $system_question_group_id);
354
-    }
355
-
356
-
357
-    /**
358
-     * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
359
-     * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
360
-     * @param $QST_system
361
-     * @return int of QST_ID for the question that corresponds to that QST_system
362
-     */
363
-    public function get_Question_ID_from_system_string($QST_system)
364
-    {
365
-        return $this->get_var(array(array('QST_system' => $QST_system)));
366
-    }
367
-
368
-
369
-    /**
370
-     * searches the db for the question with the latest question order and returns that value.
371
-     * @access public
372
-     * @return int
373
-     */
374
-    public function get_latest_question_order()
375
-    {
376
-        $columns_to_select = array(
377
-            'max_order' => array("MAX(QST_order)", "%d")
378
-        );
379
-        $max = $this->_get_all_wpdb_results(array(), ARRAY_A, $columns_to_select);
380
-        return isset($max[0], $max[0]['max_order']) ? $max[0]['max_order'] : 0;
381
-    }
382
-
383
-    /**
384
-     * Returns an array where keys are system question QST_system values,
385
-     * and values are the highest question max the admin can set on the question
386
-     * (aka the "max max"; eg, a site admin can change the zip question to have a max
387
-     * of 5, but no larger than 12)
388
-     * @return array
389
-     */
390
-    public function system_question_maxes()
391
-    {
392
-        return array(
393
-            'fname' => 45,
394
-            'lname' => 45,
395
-            'address' => 255,
396
-            'address2' => 255,
397
-            'city' => 45,
398
-            'zip' => 12,
399
-            'email' => 255,
400
-            'phone' => 45,
401
-        );
402
-    }
403
-
404
-    /**
405
-     * Given a QST_system value, gets the question's largest allowable max input.
406
-     * @see Registration_Form_Admin_Page::system_question_maxes()
407
-     * @param string $system_question_value
408
-     * @return int|float
409
-     */
410
-    public function absolute_max_for_system_question($system_question_value)
411
-    {
412
-        $maxes = $this->system_question_maxes();
413
-        if (isset($maxes[ $system_question_value ])) {
414
-            return $maxes[ $system_question_value ];
415
-        } else {
416
-            return EE_INF;
417
-        }
418
-    }
419
-
420
-
421
-    /**
422
-     * @return array
423
-     */
424
-    public function question_descriptions()
425
-    {
426
-        return $this->_question_descriptions;
427
-    }
428
-
429
-
430
-    /**
431
-     * Returns all the question types that should have an admin-defined max input length
432
-     * @return array
433
-     */
434
-    public function questionTypesWithMaxLength()
435
-    {
436
-        return (array) $this->question_types_with_max_lengh;
437
-    }
13
+	// constant used to indicate that the question type is COUNTRY
14
+	const QST_type_country = 'COUNTRY';
15
+
16
+	// constant used to indicate that the question type is DATE
17
+	const QST_type_date = 'DATE';
18
+
19
+	// constant used to indicate that the question type is DROPDOWN
20
+	const QST_type_dropdown = 'DROPDOWN';
21
+
22
+	// constant used to indicate that the question type is CHECKBOX
23
+	const QST_type_checkbox = 'CHECKBOX';
24
+
25
+	// constant used to indicate that the question type is RADIO_BTN
26
+	const QST_type_radio = 'RADIO_BTN';
27
+
28
+	// constant used to indicate that the question type is STATE
29
+	const QST_type_state = 'STATE';
30
+
31
+	// constant used to indicate that the question type is TEXT
32
+	const QST_type_text = 'TEXT';
33
+
34
+	// constant used to indicate that the question type is TEXTAREA
35
+	const QST_type_textarea = 'TEXTAREA';
36
+
37
+	// constant used to indicate that the question type is a TEXTAREA that allows simple html
38
+	const QST_type_html_textarea = 'HTML_TEXTAREA';
39
+
40
+	// constant used to indicate that the question type is an email input
41
+	const QST_type_email = 'EMAIL';
42
+
43
+	// constant used to indicate that the question type is a US-formatted phone number
44
+	const QST_type_us_phone = 'US_PHONE';
45
+
46
+	// constant used to indicate that the question type is an integer (whole number)
47
+	const QST_type_int = 'INTEGER';
48
+
49
+	// constant used to indicate that the question type is a decimal (float)
50
+	const QST_type_decimal = 'DECIMAL';
51
+
52
+	// constant used to indicate that the question type is a valid URL
53
+	const QST_type_url = 'URL';
54
+
55
+	// constant used to indicate that the question type is a YEAR
56
+	const QST_type_year = 'YEAR';
57
+
58
+	// constant used to indicate that the question type is a multi-select
59
+	const QST_type_multi_select = 'MULTI_SELECT';
60
+
61
+	/**
62
+	 * Question types that are interchangeable, even after answers have been provided for them.
63
+	 * Top-level keys are category slugs, next level is an array of question types. If question types
64
+	 * aren't in this array, it is assumed they AREN'T interchangeable with any other question types.
65
+	 *
66
+	 * @access protected
67
+	 * @var array $_question_type_categories {
68
+	 * @type string $text
69
+	 * @type string $single -answer-enum
70
+	 * @type string $multi -answer-enum
71
+	 *                    }
72
+	 */
73
+	protected $_question_type_categories = array();
74
+
75
+	/**
76
+	 * lists all the question types which should be allowed. Ideally, this will be extensible.
77
+	 *
78
+	 * @access protected
79
+	 * @var array $_allowed_question_types
80
+	 */
81
+	protected $_allowed_question_types = array();
82
+
83
+	/**
84
+	 * brief descriptions for all the question types
85
+	 *
86
+	 * @access protected
87
+	 * @var EEM_Question $_instance
88
+	 */
89
+	protected $_question_descriptions;
90
+
91
+
92
+	/**
93
+	 * Question types that should have an admin-defined max input length
94
+	 * @var array
95
+	 */
96
+	protected $question_types_with_max_lengh;
97
+
98
+
99
+	// private instance of the Attendee object
100
+	protected static $_instance = null;
101
+
102
+
103
+	/**
104
+	 * EEM_Question constructor.
105
+	 *
106
+	 * @param null $timezone
107
+	 */
108
+	protected function __construct($timezone = null)
109
+	{
110
+		$this->singular_item = __('Question', 'event_espresso');
111
+		$this->plural_item = __('Questions', 'event_espresso');
112
+		$this->_allowed_question_types = apply_filters(
113
+			'FHEE__EEM_Question__construct__allowed_question_types',
114
+			array(
115
+				EEM_Question::QST_type_text => __('Text', 'event_espresso'),
116
+				EEM_Question::QST_type_textarea => __('Textarea', 'event_espresso'),
117
+				EEM_Question::QST_type_checkbox => __('Checkboxes', 'event_espresso'),
118
+				EEM_Question::QST_type_radio => __('Radio Buttons', 'event_espresso'),
119
+				EEM_Question::QST_type_dropdown => __('Dropdown', 'event_espresso'),
120
+				EEM_Question::QST_type_state => __('State/Province Dropdown', 'event_espresso'),
121
+				EEM_Question::QST_type_country => __('Country Dropdown', 'event_espresso'),
122
+				EEM_Question::QST_type_date => __('Date Picker', 'event_espresso'),
123
+				EEM_Question::QST_type_html_textarea => __('HTML Textarea', 'event_espresso'),
124
+				EEM_Question::QST_type_email => __('Email', 'event_espresso'),
125
+				EEM_Question::QST_type_us_phone => __('USA - Format Phone', 'event_espresso'),
126
+				EEM_Question::QST_type_decimal => __('Number', 'event_espresso'),
127
+				EEM_Question::QST_type_int => __('Whole Number', 'event_espresso'),
128
+				EEM_Question::QST_type_url => __('URL', 'event_espresso'),
129
+				EEM_Question::QST_type_year => __('Year', 'event_espresso'),
130
+				EEM_Question::QST_type_multi_select => __('Multi Select', 'event_espresso')
131
+			)
132
+		);
133
+		$this->_question_descriptions = apply_filters(
134
+			'FHEE__EEM_Question__construct__question_descriptions',
135
+			array(
136
+				EEM_Question::QST_type_text => __('A single line text input field', 'event_espresso'),
137
+				EEM_Question::QST_type_textarea => __('A multi line text input field', 'event_espresso'),
138
+				EEM_Question::QST_type_checkbox => __('Allows multiple preset options to be selected', 'event_espresso'),
139
+				EEM_Question::QST_type_radio => __('Allows a single preset option to be selected', 'event_espresso'),
140
+				EEM_Question::QST_type_dropdown => __('A dropdown that allows a single selection', 'event_espresso'),
141
+				EEM_Question::QST_type_state => __('A dropdown that lists states/provinces', 'event_espresso'),
142
+				EEM_Question::QST_type_country => __('A dropdown that lists countries', 'event_espresso'),
143
+				EEM_Question::QST_type_date => __('A popup calendar that allows date selections', 'event_espresso'),
144
+				EEM_Question::QST_type_html_textarea => __('A multi line text input field that allows HTML', 'event_espresso'),
145
+				EEM_Question::QST_type_email => __('A text field that must contain a valid Email address', 'event_espresso'),
146
+				EEM_Question::QST_type_us_phone => __('A text field that must contain a valid US phone number', 'event_espresso'),
147
+				EEM_Question::QST_type_decimal => __('A text field that allows number values with decimals', 'event_espresso'),
148
+				EEM_Question::QST_type_int => __('A text field that only allows whole numbers (no decimals)', 'event_espresso'),
149
+				EEM_Question::QST_type_url => __('A text field that must contain a valid URL', 'event_espresso'),
150
+				EEM_Question::QST_type_year => __('A dropdown that lists the last 100 years', 'event_espresso'),
151
+				EEM_Question::QST_type_multi_select => __('A dropdown that allows multiple selections', 'event_espresso')
152
+			)
153
+		);
154
+		$this->_question_type_categories = (array) apply_filters(
155
+			'FHEE__EEM_Question__construct__question_type_categories',
156
+			array(
157
+				'text' => array(
158
+					EEM_Question::QST_type_text,
159
+					EEM_Question::QST_type_textarea,
160
+					EEM_Question::QST_type_date,
161
+					EEM_Question::QST_type_html_textarea,
162
+					EEM_Question::QST_type_email,
163
+					EEM_Question::QST_type_us_phone,
164
+					EEM_Question::QST_type_decimal,
165
+					EEM_Question::QST_type_int,
166
+					EEM_Question::QST_type_url,
167
+					EEM_Question::QST_type_year
168
+				),
169
+				'single-answer-enum' => array(
170
+					EEM_Question::QST_type_radio,
171
+					EEM_Question::QST_type_dropdown
172
+				),
173
+				'multi-answer-enum' => array(
174
+					EEM_Question::QST_type_checkbox,
175
+					EEM_Question::QST_type_multi_select
176
+				)
177
+			)
178
+		);
179
+		$this->question_types_with_max_lengh = apply_filters(
180
+			'FHEE__EEM_Question___construct__question_types_with_max_length',
181
+			array(
182
+				EEM_Question::QST_type_text,
183
+				EEM_Question::QST_type_textarea,
184
+				EEM_Question::QST_type_html_textarea
185
+			)
186
+		);
187
+
188
+		$this->_tables = array(
189
+			'Question' => new EE_Primary_Table('esp_question', 'QST_ID')
190
+		);
191
+		$this->_fields = array(
192
+			'Question' => array(
193
+				'QST_ID' => new EE_Primary_Key_Int_Field('QST_ID', __('Question ID', 'event_espresso')),
194
+				'QST_display_text' => new EE_Post_Content_Field('QST_display_text', __('Question Text', 'event_espresso'), true, ''),
195
+				'QST_admin_label' => new EE_Plain_Text_Field('QST_admin_label', __('Question Label (admin-only)', 'event_espresso'), true, ''),
196
+				'QST_system' => new EE_Plain_Text_Field('QST_system', __('Internal string ID for question', 'event_espresso'), false, ''),
197
+				'QST_type' => new EE_Enum_Text_Field('QST_type', __('Question Type', 'event_espresso'), false, 'TEXT', $this->_allowed_question_types),
198
+				'QST_required' => new EE_Boolean_Field('QST_required', __('Required Question?', 'event_espresso'), false, false),
199
+				'QST_required_text' => new EE_Simple_HTML_Field('QST_required_text', __('Text to Display if Not Provided', 'event_espresso'), true, ''),
200
+				'QST_order' => new EE_Integer_Field('QST_order', __('Question Order', 'event_espresso'), false, 0),
201
+				'QST_admin_only' => new EE_Boolean_Field('QST_admin_only', __('Admin-Only Question?', 'event_espresso'), false, false),
202
+				'QST_max' => new EE_Infinite_Integer_Field('QST_max', __('Max Size', 'event_espresso'), false, EE_INF),
203
+				'QST_wp_user' => new EE_WP_User_Field('QST_wp_user', __('Question Creator ID', 'event_espresso'), false),
204
+				'QST_deleted' => new EE_Trashed_Flag_Field('QST_deleted', __('Flag Indicating question was deleted', 'event_espresso'), false, false)
205
+			)
206
+		);
207
+		$this->_model_relations = array(
208
+			'Question_Group' => new EE_HABTM_Relation('Question_Group_Question'),
209
+			'Question_Option' => new EE_Has_Many_Relation(),
210
+			'Answer' => new EE_Has_Many_Relation(),
211
+			'WP_User' => new EE_Belongs_To_Relation(),
212
+			// for QST_order column
213
+			'Question_Group_Question' => new EE_Has_Many_Relation()
214
+		);
215
+		// this model is generally available for reading
216
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
217
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QST_system');
218
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QST_system');
219
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QST_system');
220
+		parent::__construct($timezone);
221
+	}
222
+
223
+	/**
224
+	 * Returns the list of allowed question types, which are normally: 'TEXT','TEXTAREA','RADIO_BTN','DROPDOWN','CHECKBOX','DATE'
225
+	 * but they can be extended
226
+	 * @return string[]
227
+	 */
228
+	public function allowed_question_types()
229
+	{
230
+		return $this->_allowed_question_types;
231
+	}
232
+
233
+	/**
234
+	 * Gets all the question types in the same category
235
+	 * @param string $question_type one of EEM_Question::allowed_question_types(
236
+	 * @return string[] like EEM_Question::allowed_question_types()
237
+	 */
238
+	public function question_types_in_same_category($question_type)
239
+	{
240
+		$question_types = array($question_type);
241
+		foreach ($this->_question_type_categories as $category => $question_types_in_category) {
242
+			if (in_array($question_type, $question_types_in_category)) {
243
+				$question_types = $question_types_in_category;
244
+				break;
245
+			}
246
+		}
247
+
248
+		return array_intersect_key($this->allowed_question_types(), array_flip($question_types));
249
+	}
250
+
251
+	/**
252
+	 * Determines if the given question type is in the given question type category
253
+	 * @param string $question_type one of EEM_Question::allowed_question_types()
254
+	 * @param string $category one of the top-level keys of EEM_Question::question_type_categories()
255
+	 * @return boolean
256
+	 */
257
+	public function question_type_is_in_category($question_type, $category)
258
+	{
259
+		if (!isset($this->_question_type_categories[ $category ])) {
260
+			return false;
261
+		}
262
+		return in_array($question_type, $this->_question_type_categories[ $category ]);
263
+	}
264
+
265
+
266
+	/**
267
+	 * Returns all the question types in the given category
268
+	 * @param string $category
269
+	 * @return array|mixed
270
+	 */
271
+	public function question_types_in_category($category)
272
+	{
273
+		if (isset($this->_question_type_categories[ $category ])) {
274
+			return $this->_question_type_categories[ $category ];
275
+		}
276
+		return array();
277
+	}
278
+
279
+
280
+	/**
281
+	 * Returns all the question types that should have question options
282
+	 * @return array
283
+	 */
284
+	public function question_types_with_options()
285
+	{
286
+		return array_merge(
287
+			$this->question_types_in_category('single-answer-enum'),
288
+			$this->question_types_in_category('multi-answer-enum')
289
+		);
290
+	}
291
+
292
+	/**
293
+	 * Returns the question type categories 2d array
294
+	 * @return array see EEM_Question::_question_type_categories
295
+	 */
296
+	public function question_type_categories()
297
+	{
298
+		return $this->_question_type_categories;
299
+	}
300
+
301
+	/**
302
+	 * Returns an array of all the QST_system values that can be allowed in the system question group
303
+	 * identified by $system_question_group_id
304
+	 * @param string $system_question_group_id QSG_system
305
+	 * @return array of system question names (QST_system)
306
+	 */
307
+	public function allowed_system_questions_in_system_question_group($system_question_group_id)
308
+	{
309
+		$question_system_ids = array();
310
+		switch ($system_question_group_id) {
311
+			case EEM_Question_Group::system_personal:
312
+				$question_system_ids = array(
313
+					EEM_Attendee::system_question_fname,
314
+					EEM_Attendee::system_question_lname,
315
+					EEM_Attendee::system_question_email,
316
+					EEM_Attendee::system_question_phone
317
+				);
318
+				break;
319
+			case EEM_Question_Group::system_address:
320
+				$question_system_ids = array(
321
+					EEM_Attendee::system_question_address,
322
+					EEM_Attendee::system_question_address2,
323
+					EEM_Attendee::system_question_city,
324
+					EEM_Attendee::system_question_state,
325
+					EEM_Attendee::system_question_country,
326
+					EEM_Attendee::system_question_zip,
327
+					EEM_Attendee::system_question_phone
328
+				);
329
+				break;
330
+		}
331
+		return apply_filters('FHEE__EEM_Question__system_questions_allowed_in_system_question_group__return', $question_system_ids, $system_question_group_id);
332
+	}
333
+
334
+	/**
335
+	 * Returns an array of all the QST_system values that are required in the system question group
336
+	 * identified by $system_question_group_id
337
+	 * @param string $system_question_group_id QSG_system
338
+	 * @return array of system question names (QST_system)
339
+	 */
340
+	public function required_system_questions_in_system_question_group($system_question_group_id)
341
+	{
342
+		$question_system_ids = null;
343
+		switch ($system_question_group_id) {
344
+			case EEM_Question_Group::system_personal:
345
+				$question_system_ids = array(
346
+					EEM_Attendee::system_question_fname,
347
+					EEM_Attendee::system_question_email,
348
+				);
349
+				break;
350
+			default:
351
+				$question_system_ids = array();
352
+		}
353
+		return apply_filters('FHEE__EEM_Question__system_questions_required_in_system_question_group', $question_system_ids, $system_question_group_id);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Gets an array for converting between QST_system and QST_IDs for system questions. Eg, if you want to know
359
+	 * which system question QST_ID corresponds to the QST_system 'city', use EEM_Question::instance()->get_Question_ID_from_system_string('city');
360
+	 * @param $QST_system
361
+	 * @return int of QST_ID for the question that corresponds to that QST_system
362
+	 */
363
+	public function get_Question_ID_from_system_string($QST_system)
364
+	{
365
+		return $this->get_var(array(array('QST_system' => $QST_system)));
366
+	}
367
+
368
+
369
+	/**
370
+	 * searches the db for the question with the latest question order and returns that value.
371
+	 * @access public
372
+	 * @return int
373
+	 */
374
+	public function get_latest_question_order()
375
+	{
376
+		$columns_to_select = array(
377
+			'max_order' => array("MAX(QST_order)", "%d")
378
+		);
379
+		$max = $this->_get_all_wpdb_results(array(), ARRAY_A, $columns_to_select);
380
+		return isset($max[0], $max[0]['max_order']) ? $max[0]['max_order'] : 0;
381
+	}
382
+
383
+	/**
384
+	 * Returns an array where keys are system question QST_system values,
385
+	 * and values are the highest question max the admin can set on the question
386
+	 * (aka the "max max"; eg, a site admin can change the zip question to have a max
387
+	 * of 5, but no larger than 12)
388
+	 * @return array
389
+	 */
390
+	public function system_question_maxes()
391
+	{
392
+		return array(
393
+			'fname' => 45,
394
+			'lname' => 45,
395
+			'address' => 255,
396
+			'address2' => 255,
397
+			'city' => 45,
398
+			'zip' => 12,
399
+			'email' => 255,
400
+			'phone' => 45,
401
+		);
402
+	}
403
+
404
+	/**
405
+	 * Given a QST_system value, gets the question's largest allowable max input.
406
+	 * @see Registration_Form_Admin_Page::system_question_maxes()
407
+	 * @param string $system_question_value
408
+	 * @return int|float
409
+	 */
410
+	public function absolute_max_for_system_question($system_question_value)
411
+	{
412
+		$maxes = $this->system_question_maxes();
413
+		if (isset($maxes[ $system_question_value ])) {
414
+			return $maxes[ $system_question_value ];
415
+		} else {
416
+			return EE_INF;
417
+		}
418
+	}
419
+
420
+
421
+	/**
422
+	 * @return array
423
+	 */
424
+	public function question_descriptions()
425
+	{
426
+		return $this->_question_descriptions;
427
+	}
428
+
429
+
430
+	/**
431
+	 * Returns all the question types that should have an admin-defined max input length
432
+	 * @return array
433
+	 */
434
+	public function questionTypesWithMaxLength()
435
+	{
436
+		return (array) $this->question_types_with_max_lengh;
437
+	}
438 438
 }
Please login to merge, or discard this patch.
acceptance_tests/tests/b-TestRegistrationSummaryCept.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -14,8 +14,8 @@  discard block
 block discarded – undo
14 14
 
15 15
 //need the MER plugin active for this test (we'll deactivate it after).
16 16
 $I->ensurePluginActive(
17
-    'event-espresso-mer-multi-event-registration',
18
-    'activated'
17
+	'event-espresso-mer-multi-event-registration',
18
+	'activated'
19 19
 );
20 20
 
21 21
 //k now we need to make sure the registration multi-status message type is active because it isn't by default
@@ -73,38 +73,38 @@  discard block
 block discarded – undo
73 73
 $I->loginAsAdmin();
74 74
 $I->amOnMessagesActivityListTablePage();
75 75
 $I->see(
76
-    '[email protected]',
77
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
78
-        'to',
79
-        'Registration Multi-status Summary',
80
-        MessagesAdmin::MESSAGE_STATUS_SENT,
81
-        '',
82
-        'Primary Registrant'
83
-    )
76
+	'[email protected]',
77
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
78
+		'to',
79
+		'Registration Multi-status Summary',
80
+		MessagesAdmin::MESSAGE_STATUS_SENT,
81
+		'',
82
+		'Primary Registrant'
83
+	)
84 84
 );
85 85
 $I->see(
86
-    '[email protected]',
87
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
88
-        'to',
89
-        'Registration Multi-status Summary',
90
-        MessagesAdmin::MESSAGE_STATUS_SENT
91
-    )
86
+	'[email protected]',
87
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
88
+		'to',
89
+		'Registration Multi-status Summary',
90
+		MessagesAdmin::MESSAGE_STATUS_SENT
91
+	)
92 92
 );
93 93
 //verify count
94 94
 $I->verifyMatchingCountofTextInMessageActivityListTableFor(
95
-    1,
96
-    '[email protected]',
97
-    'to',
98
-    'Registration Multi-status Summary',
99
-    MessagesAdmin::MESSAGE_STATUS_SENT,
100
-    'Email',
101
-    'Primary Registrant'
95
+	1,
96
+	'[email protected]',
97
+	'to',
98
+	'Registration Multi-status Summary',
99
+	MessagesAdmin::MESSAGE_STATUS_SENT,
100
+	'Email',
101
+	'Primary Registrant'
102 102
 );
103 103
 $I->verifyMatchingCountofTextInMessageActivityListTableFor(
104
-    1,
105
-    '[email protected]',
106
-    'to',
107
-    'Registration Multi-status Summary'
104
+	1,
105
+	'[email protected]',
106
+	'to',
107
+	'Registration Multi-status Summary'
108 108
 );
109 109
 
110 110
 //okay now let's do some registrations for just the first event and verify that registration multi-status summary is NOT
@@ -134,25 +134,25 @@  discard block
 block discarded – undo
134 134
 $I->loginAsAdmin();
135 135
 $I->amOnMessagesActivityListTablePage();
136 136
 $I->dontSee(
137
-    '[email protected]',
138
-    MessagesAdmin::messagesActivityListTableCellSelectorFor(
139
-        'to',
140
-        'Registration Multi-status Summary',
141
-        MessagesAdmin::MESSAGE_STATUS_SENT,
142
-        '',
143
-        'Primary Registrant'
144
-    )
137
+	'[email protected]',
138
+	MessagesAdmin::messagesActivityListTableCellSelectorFor(
139
+		'to',
140
+		'Registration Multi-status Summary',
141
+		MessagesAdmin::MESSAGE_STATUS_SENT,
142
+		'',
143
+		'Primary Registrant'
144
+	)
145 145
 );
146 146
 //there should still only be one admin multi-status summary thing.
147 147
 $I->verifyMatchingCountofTextInMessageActivityListTableFor(
148
-    1,
149
-    '[email protected]',
150
-    'to',
151
-    'Registration Multi-status Summary'
148
+	1,
149
+	'[email protected]',
150
+	'to',
151
+	'Registration Multi-status Summary'
152 152
 );
153 153
 
154 154
 //deactivate MER plugin so its not active for future tests
155 155
 $I->ensurePluginDeactivated(
156
-    'event-espresso-mer-multi-event-registration',
157
-    'plugins deactivated'
156
+	'event-espresso-mer-multi-event-registration',
157
+	'plugins deactivated'
158 158
 );
159 159
\ No newline at end of file
Please login to merge, or discard this patch.
acceptance_tests/tests/c-TestCustomMessageTemplateCept.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -18,14 +18,14 @@  discard block
 block discarded – undo
18 18
 $event_one_link = $event_two_link = $event_three_link = '';
19 19
 
20 20
 $I->wantTo(
21
-    'Test that when registrations for multiple events are completed, and those events share the same custom'
22
-    . 'template, that that custom template will be used.'
21
+	'Test that when registrations for multiple events are completed, and those events share the same custom'
22
+	. 'template, that that custom template will be used.'
23 23
 );
24 24
 
25 25
 //need the MER plugin active for this test (we'll deactivate it after).
26 26
 $I->ensurePluginActive(
27
-    'event-espresso-mer-multi-event-registration',
28
-    'activated'
27
+	'event-espresso-mer-multi-event-registration',
28
+	'activated'
29 29
 );
30 30
 
31 31
 $I->loginAsAdmin();
@@ -80,9 +80,9 @@  discard block
 block discarded – undo
80 80
 
81 81
 
82 82
 $test_registration_details = array(
83
-    'fname' => 'CTGuy',
84
-    'lname' => 'Dude',
85
-    'email' => '[email protected]'
83
+	'fname' => 'CTGuy',
84
+	'lname' => 'Dude',
85
+	'email' => '[email protected]'
86 86
 );
87 87
 
88 88
 $I->amGoingTo('Register for Event One and Event Two and verify Custom Template A was used.');
@@ -108,23 +108,23 @@  discard block
 block discarded – undo
108 108
 $I->loginAsAdmin();
109 109
 $I->amOnMessagesActivityListTablePage();
110 110
 $I->viewMessageInMessagesListTableFor(
111
-    'Registration Approved',
112
-    MessagesAdmin::MESSAGE_STATUS_SENT,
113
-    'Email',
114
-    'Registrant'
111
+	'Registration Approved',
112
+	MessagesAdmin::MESSAGE_STATUS_SENT,
113
+	'Email',
114
+	'Registrant'
115 115
 );
116 116
 $I->seeTextInViewMessageModal($custom_template_a_label);
117 117
 $I->dismissMessageModal();
118 118
 $I->deleteMessageInMessagesListTableFor(
119
-    'Registration Approved',
120
-    MessagesAdmin::MESSAGE_STATUS_SENT,
121
-    'Email',
122
-    'Registrant'
119
+	'Registration Approved',
120
+	MessagesAdmin::MESSAGE_STATUS_SENT,
121
+	'Email',
122
+	'Registrant'
123 123
 );
124 124
 
125 125
 //verify admin context
126 126
 $I->viewMessageInMessagesListTableFor(
127
-    'Registration Approved'
127
+	'Registration Approved'
128 128
 );
129 129
 $I->seeTextInViewMessageModal($custom_template_a_label);
130 130
 $I->dismissMessageModal();
@@ -153,25 +153,25 @@  discard block
 block discarded – undo
153 153
 $I->loginAsAdmin();
154 154
 $I->amOnMessagesActivityListTablePage();
155 155
 $I->viewMessageInMessagesListTableFor(
156
-    'Registration Approved',
157
-    MessagesAdmin::MESSAGE_STATUS_SENT,
158
-    'Email',
159
-    'Registrant'
156
+	'Registration Approved',
157
+	MessagesAdmin::MESSAGE_STATUS_SENT,
158
+	'Email',
159
+	'Registrant'
160 160
 );
161 161
 $I->waitForElementVisible(MessagesAdmin::MESSAGES_LIST_TABLE_VIEW_MESSAGE_DIALOG_CONTAINER_SELECTOR);
162 162
 $I->dontSeeTextInViewMessageModal($custom_template_a_label);
163 163
 $I->dontSeeTextInViewMessageModal($custom_template_b_label);
164 164
 $I->dismissMessageModal();
165 165
 $I->deleteMessageInMessagesListTableFor(
166
-    'Registration Approved',
167
-    MessagesAdmin::MESSAGE_STATUS_SENT,
168
-    'Email',
169
-    'Registrant'
166
+	'Registration Approved',
167
+	MessagesAdmin::MESSAGE_STATUS_SENT,
168
+	'Email',
169
+	'Registrant'
170 170
 );
171 171
 
172 172
 //verify admin context
173 173
 $I->viewMessageInMessagesListTableFor(
174
-    'Registration Approved'
174
+	'Registration Approved'
175 175
 );
176 176
 $I->waitForElementVisible(MessagesAdmin::MESSAGES_LIST_TABLE_VIEW_MESSAGE_DIALOG_CONTAINER_SELECTOR);
177 177
 $I->dontSee($custom_template_a_label);
@@ -183,6 +183,6 @@  discard block
 block discarded – undo
183 183
 
184 184
 //deactivate MER plugin so its not active for future tests
185 185
 $I->ensurePluginDeactivated(
186
-    'event-espresso-mer-multi-event-registration',
187
-    'plugins deactivated'
186
+	'event-espresso-mer-multi-event-registration',
187
+	'plugins deactivated'
188 188
 );
189 189
\ No newline at end of file
Please login to merge, or discard this patch.
acceptance_tests/Helpers/RegistrationsAdmin.php 1 patch
Indentation   +134 added lines, -134 removed lines patch added patch discarded remove patch
@@ -15,139 +15,139 @@
 block discarded – undo
15 15
 trait RegistrationsAdmin
16 16
 {
17 17
 
18
-    /**
19
-     * This will select all checkboxes on a registration list table for the given array of
20
-     * registration ids.
21
-     * Assumes the actor is on a list table page for registrations.
22
-     * @param $registration_ids
23
-     */
24
-    public function selectBulkActionCheckboxesForRegistrationIds(array $registration_ids)
25
-    {
26
-        foreach ($registration_ids as $registration_id) {
27
-            $this->actor()->checkOption(
28
-                RegistrationsAdminPage::listTableCheckBoxSelectorForRegistrationId($registration_id)
29
-            );
30
-        }
31
-    }
32
-
33
-
34
-    /**
35
-     * Navigates the actor to the default registration list table page.
36
-     * @param string $additional_params
37
-     */
38
-    public function amOnDefaultRegistrationsListTableAdminPage($additional_params = '')
39
-    {
40
-        $this->actor()->amOnAdminPage(
41
-            RegistrationsAdminPage::registrationsDefaultAdminListTableUrl($additional_params)
42
-        );
43
-        //wait for page to fully load
44
-        $this->actor()->wait(5);
45
-    }
46
-
47
-
48
-    /**
49
-     * Will enter the provided value in the registration list table search field and execute a search for that value.
50
-     * @param string $search_text
51
-     */
52
-    public function searchForRegistrationOnRegistrationListTableWithText($search_text)
53
-    {
54
-        $this->amOnDefaultRegistrationsListTableAdminPage();
55
-        $this->actor()->fillField(RegistrationsAdminPage::SEARCH_INPUT_SELECTOR_LIST_TABLE_REGISTRATION, $search_text);
56
-        $this->actor()->click(CoreAdmin::LIST_TABLE_SEARCH_SUBMIT_SELECTOR);
57
-        $this->actor()->waitForText('Displaying search results for');
58
-    }
59
-
60
-
61
-
62
-    /**
63
-     * This will filter the registration list table to view registrations for the given event id.
64
-     * Assumption is made that you are logged into the admin but you do not need to be on the registration list table
65
-     * page.
66
-     *
67
-     * @param int $event_id  The id of the event viewing registrations for.
68
-     */
69
-    public function amViewingRegistrationsForEvent($event_id)
70
-    {
71
-        $this->actor()->amOnDefaultEventsListTablePage();
72
-        $this->actor()->click(EventsAdmin::listTableActionLinkRegistrationsForEvent($event_id));
73
-        $this->actor()->waitForText('Viewing registrations for the event');
74
-    }
75
-
76
-
77
-    /**
78
-     * This helper will initiate registering for the given event via the backend.
79
-     * @param int $event_id  The event to initiate registration for.
80
-     */
81
-    public function amOnAdminRegistrationPageForEvent($event_id)
82
-    {
83
-        $this->actor()->amViewingRegistrationsForEvent($event_id);
84
-        $this->actor()->click(RegistrationsAdminPage::BUTTON_ADD_NEW_REGISTRATION);
85
-        $this->actor()->waitForText('Adding Registration For');
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * This clicks the View Details Link for Registration with the given Id
92
-     * @param $registration_id
93
-     */
94
-    public function clickViewDetailsLinkForRegistrationWithId($registration_id)
95
-    {
96
-        $this->actor()->click(RegistrationsAdminPage::viewDetailsLinkSelectorForRegistrationId($registration_id));
97
-    }
98
-
99
-
100
-    /**
101
-     * /**
102
-     * This assumes you are on the admin details page for a registration in EE.  It selects the given status in the
103
-     * dropdown for changing registration status.
104
-     *
105
-     * @param string $status_label_or_value  Either the label for the dropdown option or the value for the option.
106
-     * @param $status_label_or_value
107
-     */
108
-    public function selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value)
109
-    {
110
-        $this->actor()->selectOption(
111
-            RegistrationsAdminPage::DROPDOWN_REGISTRATION_STATUS,
112
-            $status_label_or_value
113
-        );
114
-    }
115
-
116
-
117
-    /**
118
-     * This selects (or deselects) the "Send Related Messages" checkbox on the Registration Details page.
119
-     * @param bool $send_related_messages
120
-     */
121
-    public function selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages = true)
122
-    {
123
-        $send_related_messages
124
-            ? $this->actor()->selectOption(
125
-                RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES,
126
-                'Yes'
127
-            )
128
-            : $this->actor()->selecOption(
129
-                RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES,
130
-                'No'
131
-            );
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * This assumes you are on the admin details page for a registration in EE.  It selects the given status in the
138
-     * dropdown for changing registration status and submits the change.
139
-     *
140
-     * @param string $status_label_or_value  Either the label for the dropdown option or the value for the option.
141
-     * @param bool   $send_related_messages  Whether or not to send related messages after changing the bulk action.
142
-     */
143
-    public function changeRegistrationStatusOnRegistrationDetailsPageTo(
144
-        $status_label_or_value,
145
-        $send_related_messages = true
146
-    ) {
147
-        $this->actor()->selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value);
148
-        $this->actor()->selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages);
149
-        $this->actor()->click(RegistrationsAdminPage::BUTTON_UPDATE_REGISTRATION_STATUS);
150
-        $this->actor()->waitForText('Registration status has been set to');
151
-    }
18
+	/**
19
+	 * This will select all checkboxes on a registration list table for the given array of
20
+	 * registration ids.
21
+	 * Assumes the actor is on a list table page for registrations.
22
+	 * @param $registration_ids
23
+	 */
24
+	public function selectBulkActionCheckboxesForRegistrationIds(array $registration_ids)
25
+	{
26
+		foreach ($registration_ids as $registration_id) {
27
+			$this->actor()->checkOption(
28
+				RegistrationsAdminPage::listTableCheckBoxSelectorForRegistrationId($registration_id)
29
+			);
30
+		}
31
+	}
32
+
33
+
34
+	/**
35
+	 * Navigates the actor to the default registration list table page.
36
+	 * @param string $additional_params
37
+	 */
38
+	public function amOnDefaultRegistrationsListTableAdminPage($additional_params = '')
39
+	{
40
+		$this->actor()->amOnAdminPage(
41
+			RegistrationsAdminPage::registrationsDefaultAdminListTableUrl($additional_params)
42
+		);
43
+		//wait for page to fully load
44
+		$this->actor()->wait(5);
45
+	}
46
+
47
+
48
+	/**
49
+	 * Will enter the provided value in the registration list table search field and execute a search for that value.
50
+	 * @param string $search_text
51
+	 */
52
+	public function searchForRegistrationOnRegistrationListTableWithText($search_text)
53
+	{
54
+		$this->amOnDefaultRegistrationsListTableAdminPage();
55
+		$this->actor()->fillField(RegistrationsAdminPage::SEARCH_INPUT_SELECTOR_LIST_TABLE_REGISTRATION, $search_text);
56
+		$this->actor()->click(CoreAdmin::LIST_TABLE_SEARCH_SUBMIT_SELECTOR);
57
+		$this->actor()->waitForText('Displaying search results for');
58
+	}
59
+
60
+
61
+
62
+	/**
63
+	 * This will filter the registration list table to view registrations for the given event id.
64
+	 * Assumption is made that you are logged into the admin but you do not need to be on the registration list table
65
+	 * page.
66
+	 *
67
+	 * @param int $event_id  The id of the event viewing registrations for.
68
+	 */
69
+	public function amViewingRegistrationsForEvent($event_id)
70
+	{
71
+		$this->actor()->amOnDefaultEventsListTablePage();
72
+		$this->actor()->click(EventsAdmin::listTableActionLinkRegistrationsForEvent($event_id));
73
+		$this->actor()->waitForText('Viewing registrations for the event');
74
+	}
75
+
76
+
77
+	/**
78
+	 * This helper will initiate registering for the given event via the backend.
79
+	 * @param int $event_id  The event to initiate registration for.
80
+	 */
81
+	public function amOnAdminRegistrationPageForEvent($event_id)
82
+	{
83
+		$this->actor()->amViewingRegistrationsForEvent($event_id);
84
+		$this->actor()->click(RegistrationsAdminPage::BUTTON_ADD_NEW_REGISTRATION);
85
+		$this->actor()->waitForText('Adding Registration For');
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * This clicks the View Details Link for Registration with the given Id
92
+	 * @param $registration_id
93
+	 */
94
+	public function clickViewDetailsLinkForRegistrationWithId($registration_id)
95
+	{
96
+		$this->actor()->click(RegistrationsAdminPage::viewDetailsLinkSelectorForRegistrationId($registration_id));
97
+	}
98
+
99
+
100
+	/**
101
+	 * /**
102
+	 * This assumes you are on the admin details page for a registration in EE.  It selects the given status in the
103
+	 * dropdown for changing registration status.
104
+	 *
105
+	 * @param string $status_label_or_value  Either the label for the dropdown option or the value for the option.
106
+	 * @param $status_label_or_value
107
+	 */
108
+	public function selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value)
109
+	{
110
+		$this->actor()->selectOption(
111
+			RegistrationsAdminPage::DROPDOWN_REGISTRATION_STATUS,
112
+			$status_label_or_value
113
+		);
114
+	}
115
+
116
+
117
+	/**
118
+	 * This selects (or deselects) the "Send Related Messages" checkbox on the Registration Details page.
119
+	 * @param bool $send_related_messages
120
+	 */
121
+	public function selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages = true)
122
+	{
123
+		$send_related_messages
124
+			? $this->actor()->selectOption(
125
+				RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES,
126
+				'Yes'
127
+			)
128
+			: $this->actor()->selecOption(
129
+				RegistrationsAdminPage::DROPDOWN_SEND_RELATED_MESSAGES,
130
+				'No'
131
+			);
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * This assumes you are on the admin details page for a registration in EE.  It selects the given status in the
138
+	 * dropdown for changing registration status and submits the change.
139
+	 *
140
+	 * @param string $status_label_or_value  Either the label for the dropdown option or the value for the option.
141
+	 * @param bool   $send_related_messages  Whether or not to send related messages after changing the bulk action.
142
+	 */
143
+	public function changeRegistrationStatusOnRegistrationDetailsPageTo(
144
+		$status_label_or_value,
145
+		$send_related_messages = true
146
+	) {
147
+		$this->actor()->selectRegistrationStatusOnRegistrationDetailsPageFor($status_label_or_value);
148
+		$this->actor()->selectSendRelatedMessagesOptionOnRegistrationDetailsPage($send_related_messages);
149
+		$this->actor()->click(RegistrationsAdminPage::BUTTON_UPDATE_REGISTRATION_STATUS);
150
+		$this->actor()->waitForText('Registration status has been set to');
151
+	}
152 152
 
153 153
 }
154 154
\ No newline at end of file
Please login to merge, or discard this patch.