Completed
Branch FET-8385-datetime-ticket-selec... (957a7a)
by
unknown
79:05 queued 67:51
created

EEM_Datetime::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 61
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 44
nc 1
nop 1
dl 0
loc 61
rs 9.5147
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
    exit('No direct script access allowed');
3
}
4
/**
5
 * Class Datetime Model
6
 *
7
 * @package               Event Espresso
8
 * @subpackage            includes/models/
9
 * @author                Michael Nelson, Brent Christensen
10
 */
11
class EEM_Datetime extends EEM_Soft_Delete_Base
12
{
13
14
    /**
15
     * @var EEM_Datetime $_instance
16
     */
17
    protected static $_instance;
18
19
20
21
    /**
22
     *        private constructor to prevent direct creation
23
     *
24
     * @Constructor
25
     * @access private
26
     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
27
     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
28
     *                         date time model field objects.  Default is NULL (and will be assumed using the set
29
     *                         timezone in the 'timezone_string' wp option)
30
     * @throws \EE_Error
31
     */
32
    protected function __construct($timezone)
33
    {
34
        $this->singular_item = __('Datetime', 'event_espresso');
35
        $this->plural_item = __('Datetimes', 'event_espresso');
36
        $this->_tables = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Datetime' => new ...p_datetime', 'DTT_ID')) of type array<string,object<EE_P...ct<EE_Primary_Table>"}> is incompatible with the declared type array<integer,object<EE_Table_Base>> of property $_tables.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
37
            'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
38
        );
39
        $this->_fields = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Datetime' => arra...esso'), false, false))) of type array<string,array<strin...shed_Flag_Field>\"}>"}> is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_fields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
40
            'Datetime' => array(
41
                'DTT_ID'          => new EE_Primary_Key_Int_Field('DTT_ID', __('Datetime ID', 'event_espresso')),
42
                'EVT_ID'          => new EE_Foreign_Key_Int_Field(
43
                    'EVT_ID', __('Event ID', 'event_espresso'), false, 0, 'Event'
44
                ),
45
                'DTT_name'        => new EE_Plain_Text_Field(
46
                    'DTT_name', __('Datetime Name', 'event_espresso'), false, ''
47
                ),
48
                'DTT_description' => new EE_Post_Content_Field(
49
                    'DTT_description', __('Description for Datetime', 'event_espresso'), false, ''
50
                ),
51
                'DTT_EVT_start'   => new EE_Datetime_Field(
52
                    'DTT_EVT_start', __('Start time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
53
                    $timezone
54
                ),
55
                'DTT_EVT_end'     => new EE_Datetime_Field(
56
                    'DTT_EVT_end', __('End time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
57
                    $timezone
58
                ),
59
                'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
60
                    'DTT_reg_limit', __('Registration Limit for this time', 'event_espresso'), true, EE_INF),
61
                'DTT_sold'        => new EE_Integer_Field(
62
                    'DTT_sold', __('How many sales for this Datetime that have occurred', 'event_espresso'), true, 0
63
                ),
64
                'DTT_is_primary'  => new EE_Boolean_Field(
65
                    'DTT_is_primary', __('Flag indicating datetime is primary one for event', 'event_espresso'),
66
                    false, false
67
                ),
68
                'DTT_order'       => new EE_Integer_Field(
69
                    'DTT_order', __('The order in which the Datetime is displayed', 'event_espresso'), false, 0
70
                ),
71
                'DTT_parent'      => new EE_Integer_Field(
72
                    'DTT_parent', __('Indicates what DTT_ID is the parent of this DTT_ID'), true, 0
73
                ),
74
                'DTT_deleted'     => new EE_Trashed_Flag_Field(
75
                    'DTT_deleted', __('Flag indicating datetime is archived', 'event_espresso'), false, false
76
                ),
77
            ),
78
        );
79
        $this->_model_relations = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Ticket' => new \E...EE_Has_Many_Relation()) of type array<string,object<EE_H...E_Has_Many_Relation>"}> is incompatible with the declared type array<integer,object<EE_Model_Relation_Base>> of property $_model_relations.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
80
            'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
0 ignored issues
show
Documentation introduced by
'Datetime_Ticket' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
81
            'Event'   => new EE_Belongs_To_Relation(),
82
            'Checkin' => new EE_Has_Many_Relation(),
83
        );
84
        $this->_model_chain_to_wp_user = 'Event';
85
        //this model is generally available for reading
86
        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public('Event');
87
        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Event_Related_Protected('Event');
88
        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected('Event');
89
        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Event_Related_Protected('Event',
90
            EEM_Base::caps_edit);
91
        parent::__construct($timezone);
92
    }
93
94
95
96
    /**
97
     * create new blank datetime
98
     *
99
     * @access public
100
     * @return EE_Datetime[] array on success, FALSE on fail
101
     * @throws \EE_Error
102
     */
103
    public function create_new_blank_datetime()
104
    {
105
        $blank_datetime = EE_Datetime::new_instance(
106
            array(
107
                'DTT_EVT_start' => $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS,
108
                'DTT_EVT_end'   => $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS,
109
                'DTT_order'     => 1,
110
                'DTT_reg_limit' => EE_INF,
111
            ),
112
            $this->_timezone
113
        );
114
        $blank_datetime->set_start_time($this->convert_datetime_for_query('DTT_EVT_start', '8am', 'ga',
0 ignored issues
show
Documentation introduced by
$this->convert_datetime_...'ga', $this->_timezone) is of type object<DateTime>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
115
            $this->_timezone));
116
        $blank_datetime->set_end_time($this->convert_datetime_for_query('DTT_EVT_end', '5pm', 'ga', $this->_timezone));
0 ignored issues
show
Documentation introduced by
$this->convert_datetime_...'ga', $this->_timezone) is of type object<DateTime>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
117
        return array($blank_datetime);
118
    }
119
120
121
122
    /**
123
     * get event start date from db
124
     *
125
     * @access public
126
     * @param  int $EVT_ID
127
     * @return EE_Datetime[] array on success, FALSE on fail
128
     * @throws \EE_Error
129
     */
130
    public function get_all_event_dates($EVT_ID = 0)
131
    {
132
        if ( ! $EVT_ID) { // on add_new_event event_id gets set to 0
133
            return $this->create_new_blank_datetime();
134
        }
135
        $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
136
        if (empty($results)) {
137
            return $this->create_new_blank_datetime();
138
        }
139
        return $results;
140
    }
141
142
143
144
    /**
145
     * get all datetimes attached to an event ordered by the DTT_order field
146
     *
147
     * @public
148
     * @param  int    $EVT_ID     event id
149
     * @param boolean $include_expired
150
     * @param boolean $include_deleted
151
     * @param  int    $limit      If included then limit the count of results by
152
     *                            the given number
153
     * @return EE_Datetime[]
154
     * @throws \EE_Error
155
     */
156
    public function get_datetimes_for_event_ordered_by_DTT_order(
157
        $EVT_ID,
158
        $include_expired = true,
159
        $include_deleted = true,
160
        $limit = null
161
    ) {
162
        //sanitize EVT_ID
163
        $EVT_ID = absint($EVT_ID);
164
        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
165
        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
166
        $where_params = array('Event.EVT_ID' => $EVT_ID);
167
        $query_params = ! empty($limit)
168
            ? array(
169
                $where_params,
170
                'limit'                    => $limit,
171
                'order_by'                 => array('DTT_order' => 'ASC'),
172
                'default_where_conditions' => 'none',
173
            )
174
            : array(
175
                $where_params,
176
                'order_by'                 => array('DTT_order' => 'ASC'),
177
                'default_where_conditions' => 'none',
178
            );
179
        if ( ! $include_expired) {
180
            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
181
        }
182
        if ($include_deleted) {
183
            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
184
        }
185
        /** @var EE_Datetime[] $result */
186
        $result = $this->get_all($query_params);
187
        $this->assume_values_already_prepared_by_model_object($old_assumption);
0 ignored issues
show
Documentation introduced by
$old_assumption is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188
        return $result;
189
    }
190
191
192
193
    /**
194
     * Gets the datetimes for the event (with the given limit), and orders them by "importance". By importance, we mean
195
     * that the primary datetimes are most important (DEPRECATED FOR NOW), and then the earlier datetimes are the most
196
     * important. Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
197
     *
198
     * @param int $EVT_ID
199
     * @param int $limit
200
     * @return EE_Datetime[]|EE_Base_Class[]
201
     * @throws \EE_Error
202
     */
203
    public function get_datetimes_for_event_ordered_by_importance($EVT_ID = 0, $limit = null)
204
    {
205
        return $this->get_all(
206
            array(
207
                array('Event.EVT_ID' => $EVT_ID),
208
                'limit'                    => $limit,
209
                'order_by'                 => array('DTT_EVT_start' => 'ASC'),
210
                'default_where_conditions' => 'none',
211
            )
212
        );
213
    }
214
215
216
217
    /**
218
     * @param int     $EVT_ID
219
     * @param boolean $include_expired
220
     * @param boolean $include_deleted
221
     * @return EE_Datetime
222
     * @throws \EE_Error
223
     */
224
    public function get_oldest_datetime_for_event($EVT_ID, $include_expired = false, $include_deleted = false)
225
    {
226
        $results = $this->get_datetimes_for_event_ordered_by_start_time($EVT_ID, $include_expired, $include_deleted, 1);
227
        if ($results) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type EE_Datetime[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
228
            return array_shift($results);
229
        } else {
230
            return null;
231
        }
232
    }
233
234
235
236
    /**
237
     * Gets the 'primary' datetime for an event.
238
     *
239
     * @param int  $EVT_ID
240
     * @param bool $try_to_exclude_expired
241
     * @param bool $try_to_exclude_deleted
242
     * @return \EE_Datetime
243
     * @throws \EE_Error
244
     */
245
    public function get_primary_datetime_for_event(
246
        $EVT_ID,
247
        $try_to_exclude_expired = true,
248
        $try_to_exclude_deleted = true
249
    ) {
250
        if ($try_to_exclude_expired) {
251
            $non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
252
            if ($non_expired) {
253
                return $non_expired;
254
            }
255
        }
256
        if ($try_to_exclude_deleted) {
257
            $expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $expired_even is correct as $this->get_oldest_dateti...or_event($EVT_ID, true) (which targets EEM_Datetime::get_oldest_datetime_for_event()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
258
            if ($expired_even) {
259
                return $expired_even;
260
            }
261
        }
262
        return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
263
    }
264
265
266
267
    /**
268
     * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
269
     * only by start date
270
     *
271
     * @param int     $EVT_ID
272
     * @param boolean $include_expired
273
     * @param boolean $include_deleted
274
     * @param int     $limit
275
     * @return EE_Datetime[]
276
     * @throws \EE_Error
277
     */
278 View Code Duplication
    public function get_datetimes_for_event_ordered_by_start_time(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
279
        $EVT_ID,
280
        $include_expired = true,
281
        $include_deleted = true,
282
        $limit = null
283
    ) {
284
        //sanitize EVT_ID
285
        $EVT_ID = absint($EVT_ID);
286
        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
287
        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
288
        $query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
289
        if ( ! $include_expired) {
290
            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
291
        }
292
        if ($include_deleted) {
293
            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
294
        }
295
        if ($limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
296
            $query_params['limit'] = $limit;
297
        }
298
        /** @var EE_Datetime[] $result */
299
        $result = $this->get_all($query_params);
300
        $this->assume_values_already_prepared_by_model_object($old_assumption);
0 ignored issues
show
Documentation introduced by
$old_assumption is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
301
        return $result;
302
    }
303
304
305
306
    /**
307
     * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
308
     * only by start date
309
     *
310
     * @param int     $TKT_ID
311
     * @param boolean $include_expired
312
     * @param boolean $include_deleted
313
     * @param int     $limit
314
     * @return EE_Datetime[]
315
     * @throws \EE_Error
316
     */
317 View Code Duplication
    public function get_datetimes_for_ticket_ordered_by_start_time(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
318
        $TKT_ID,
319
        $include_expired = true,
320
        $include_deleted = true,
321
        $limit = null
322
    ) {
323
        //sanitize TKT_ID
324
        $TKT_ID = absint($TKT_ID);
325
        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
326
        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
327
        $query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
328
        if ( ! $include_expired) {
329
            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
330
        }
331
        if ($include_deleted) {
332
            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
333
        }
334
        if ($limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
335
            $query_params['limit'] = $limit;
336
        }
337
        /** @var EE_Datetime[] $result */
338
        $result = $this->get_all($query_params);
339
        $this->assume_values_already_prepared_by_model_object($old_assumption);
0 ignored issues
show
Documentation introduced by
$old_assumption is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
340
        return $result;
341
    }
342
343
344
345
    /**
346
     * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
347
     * datetimes.
348
     *
349
     * @param  int      $TKT_ID          ID of ticket to retrieve the datetimes for
350
     * @param  boolean  $include_expired whether to include expired datetimes or not
351
     * @param  boolean  $include_deleted whether to include trashed datetimes or not.
352
     * @param  int|null $limit           if null, no limit, if int then limit results by
353
     *                                   that number
354
     * @return EE_Datetime[]
355
     * @throws \EE_Error
356
     */
357 View Code Duplication
    public function get_datetimes_for_ticket_ordered_by_DTT_order(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
358
        $TKT_ID,
359
        $include_expired = true,
360
        $include_deleted = true,
361
        $limit = null
362
    ) {
363
        //sanitize id.
364
        $TKT_ID = absint($TKT_ID);
365
        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
366
        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
367
        $where_params = array('Ticket.TKT_ID' => $TKT_ID);
368
        $query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
369
        if ( ! $include_expired) {
370
            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
371
        }
372
        if ($include_deleted) {
373
            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
374
        }
375
        if ($limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
376
            $query_params['limit'] = $limit;
377
        }
378
        /** @var EE_Datetime[] $result */
379
        $result = $this->get_all($query_params);
380
        $this->assume_values_already_prepared_by_model_object($old_assumption);
0 ignored issues
show
Documentation introduced by
$old_assumption is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
381
        return $result;
382
    }
383
384
385
386
    /**
387
     * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
388
     * reason it doesn't exist, we consider the earliest event the most important)
389
     *
390
     * @param int $EVT_ID
391
     * @return EE_Datetime
392
     * @throws \EE_Error
393
     */
394
    public function get_most_important_datetime_for_event($EVT_ID)
395
    {
396
        $results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
397
        if ($results) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
398
            return array_shift($results);
399
        } else {
400
            return null;
401
        }
402
    }
403
404
405
406
    /**
407
     * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
408
     * grouped by month and year.
409
     *
410
     * @param  array  $where_params      Array of query_params as described in the comments for EEM_Base::get_all()
411
     * @param  string $evt_active_status A string representing the evt active status to filter the months by.
412
     *                                   Can be:
413
     *                                   - '' = no filter
414
     *                                   - upcoming = Published events with at least one upcoming datetime.
415
     *                                   - expired = Events with all datetimes expired.
416
     *                                   - active = Events that are published and have at least one datetime that
417
     *                                   starts before now and ends after now.
418
     *                                   - inactive = Events that are either not published.
419
     * @return EE_Base_Class[]
420
     * @throws \EE_Error
421
     */
422
    public function get_dtt_months_and_years($where_params, $evt_active_status = '')
423
    {
424
        $current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
425
        $current_time_for_DTT_EVT_end = $this->current_time_for_query('DTT_EVT_end');
426
        switch ($evt_active_status) {
427
            case 'upcoming' :
428
                $where_params['Event.status'] = 'publish';
429
                //if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
430
                if (isset($where_params['DTT_EVT_start'])) {
431
                    $where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
432
                }
433
                $where_params['DTT_EVT_start'] = array('>', $current_time_for_DTT_EVT_start);
434
                break;
435
            case 'expired' :
436
                if (isset($where_params['Event.status'])) {
437
                    unset($where_params['Event.status']);
438
                }
439
                //get events to exclude
440
                $exclude_query[0] = array_merge($where_params,
0 ignored issues
show
Coding Style Comprehensibility introduced by
$exclude_query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exclude_query = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
441
                    array('DTT_EVT_end' => array('>', $current_time_for_DTT_EVT_end)));
442
                //first get all events that have datetimes where its not expired.
443
                $event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Datetime.EVT_ID');
444
                $event_ids = array_keys($event_ids);
445
                if (isset($where_params['DTT_EVT_end'])) {
446
                    $where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
447
                }
448
                $where_params['DTT_EVT_end'] = array('<', $current_time_for_DTT_EVT_end);
449
                $where_params['Event.EVT_ID'] = array('NOT IN', $event_ids);
450
                break;
451
            case 'active' :
452
                $where_params['Event.status'] = 'publish';
453
                if (isset($where_params['DTT_EVT_start'])) {
454
                    $where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
455
                }
456
                if (isset($where_params['Datetime.DTT_EVT_end'])) {
457
                    $where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
458
                }
459
                $where_params['DTT_EVT_start'] = array('<', $current_time_for_DTT_EVT_start);
460
                $where_params['DTT_EVT_end'] = array('>', $current_time_for_DTT_EVT_end);
461
                break;
462
            case 'inactive' :
463
                if (isset($where_params['Event.status'])) {
464
                    unset($where_params['Event.status']);
465
                }
466
                if (isset($where_params['OR'])) {
467
                    $where_params['AND']['OR'] = $where_params['OR'];
468
                }
469
                if (isset($where_params['DTT_EVT_end'])) {
470
                    $where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
471
                    unset($where_params['DTT_EVT_end']);
472
                }
473
                if (isset($where_params['DTT_EVT_start'])) {
474
                    $where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
475
                    unset($where_params['DTT_EVT_start']);
476
                }
477
                $where_params['AND']['Event.status'] = array('!=', 'publish');
478
                break;
479
        }
480
        $query_params[0] = $where_params;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$query_params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_params = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
481
        $query_params['group_by'] = array('dtt_year', 'dtt_month');
482
        $query_params['order_by'] = array('DTT_EVT_start' => 'DESC');
483
        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'DTT_EVT_start');
484
        $columns_to_select = array(
485
            'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
486
            'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
487
            'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
488
        );
489
        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
490
    }
491
492
493
494
    /**
495
     * Updates the DTT_sold attribute on each datetime (based on the registrations
496
     * for the tickets for each datetime)
497
     *
498
     * @param EE_Datetime[] $datetimes
499
     */
500
    public function update_sold($datetimes)
501
    {
502
        foreach ($datetimes as $datetime) {
503
            $datetime->update_sold();
504
        }
505
    }
506
507
508
509
    /**
510
     *    Gets the total number of tickets available at a particular datetime
511
     *    (does NOT take into account the datetime's spaces available)
512
     *
513
     * @param int   $DTT_ID
514
     * @param array $query_params
515
     * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
516
     *             tickets attached to datetime then FALSE is returned.
517
     */
518
    public function sum_tickets_currently_available_at_datetime($DTT_ID, array $query_params = array())
519
    {
520
        $datetime = $this->get_one_by_ID($DTT_ID);
521
        if ($datetime instanceof EE_Datetime) {
522
            return $datetime->tickets_remaining($query_params);
523
        }
524
        return 0;
525
    }
526
527
528
529
    /**
530
     * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
531
     *
532
     * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
533
     *                                 stati you want counts for as values in the array.  An empty array returns counts
534
     *                                 for all valid stati.
535
     * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
536
     *                                 only for Datetimes connected to a specific event, or specific ticket.
537
     * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
538
     * @throws \EE_Error
539
     *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming EE_Datetime::expired
540
     */
541
    public function get_datetime_counts_by_status(array $stati_to_include = array(), array $query_params = array())
542
    {
543
        //only accept where conditions for this query.
544
        $_where = isset($query_params[0]) ? $query_params[0] : array();
545
        $status_query_args = array(
546
            EE_Datetime::active   => array_merge(
547
                $_where,
548
                array('DTT_EVT_start' => array('<', time()), 'DTT_EVT_end' => array('>', time()))
549
            ),
550
            EE_Datetime::upcoming => array_merge(
551
                $_where,
552
                array('DTT_EVT_start' => array('>', time()))
553
            ),
554
            EE_Datetime::expired  => array_merge(
555
                $_where,
556
                array('DTT_EVT_end' => array('<', time()))
557
            ),
558
        );
559
        if ( ! empty($stati_to_include)) {
560
            foreach (array_keys($status_query_args) as $status) {
561
                if ( ! in_array($status, $stati_to_include, true)) {
562
                    unset($status_query_args[$status]);
563
                }
564
            }
565
        }
566
        //loop through and query counts for each stati.
567
        $status_query_results = array();
568
        foreach ($status_query_args as $status => $status_where_conditions) {
569
            $status_query_results[$status] = EEM_Datetime::count(array($status_where_conditions), 'DTT_ID', true);
570
        }
571
        return $status_query_results;
572
    }
573
574
575
576
    /**
577
     * Returns the specific count for a given Datetime status matching any given query_params.
578
     *
579
     * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
580
     * @param array  $query_params
581
     * @return int
582
     * @throws \EE_Error
583
     */
584
    public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
585
    {
586
        $count = $this->get_datetime_counts_by_status(array($status), $query_params);
587
        return ! empty($count[$status]) ? $count[$status] : 0;
588
    }
589
590
591
592
}
593
// End of file EEM_Datetime.model.php
594
// Location: /includes/models/EEM_Datetime.model.php
595