Completed
Branch FET-9046-messages-queue (acf360)
by
unknown
1260:33 queued 1235:57
created

EEM_Message::create_default_object()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
2
/**
3
 * Message Model
4
 *
5
 * @package			Event Espresso
6
 * @subpackage		models
7
 * @author			Darren Ethier
8
 */
9
class EEM_Message extends EEM_Base implements EEI_Query_Filter {
10
11
	// private instance of the Message object
12
	protected static $_instance = null;
13
14
15
	/**
16
	 * This priority indicates a message should be generated and sent ASAP
17
	 * @type int
18
	 */
19
	const priority_high = 10;
20
21
22
23
24
	/**
25
	 * This priority indicates a message should be generated ASAP and queued for sending.
26
	 * @type
27
	 */
28
	const priority_medium = 20;
29
30
31
32
33
	/**
34
	 * This priority indicates a message should be queued for generating.
35
	 * @type int
36
	 */
37
	const priority_low = 30;
38
39
40
41
	/**
42
	 * indicates this message was sent at the time modified
43
	 */
44
	const status_sent = 'MSN';
45
46
47
	/**
48
	 * indicates this message is waiting to be sent
49
	 */
50
	const status_idle = 'MID';
51
52
53
	/**
54
	 * indicates an attempt was a made to send this message
55
	 * at the scheduled time, but it failed at the time modified
56
	 */
57
	const status_failed = 'MFL';
58
59
60
	/**
61
	 * indicates the message has been flagged for resending (at the time modified).
62
	 */
63
	const status_resend = 'MRS';
64
65
66
	/**
67
	 * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as this
68
	 * status when added to the queue.
69
	 */
70
	const status_incomplete = 'MIC';
71
72
73
74
75
	/**
76
	 * Indicates everything was generated fine for the message, however, the messenger was unable to send.
77
	 * This status means that its possible to retry sending the message.
78
	 */
79
	const status_retry = 'MRT';
80
81
82
83
84
85
	/**
86
	 *	Private constructor to prevent direct creation.
87
	 *
88
	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and
89
	 *                         any incoming timezone data that gets saved).  Note this just sends the timezone info to the
90
	 *                         date time model field objects.  Default is null (and will be assumed using the set timezone
91
	 *                         in the 'timezone_string' wp option)
92
	 *
93
	 * @return EEM_Message
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
94
	 */
95
	protected function __construct( $timezone = null ) {
96
		$this->singular_item = __('Message','event_espresso');
97
		$this->plural_item = __('Messages','event_espresso');
98
99
		//used for token generator
100
		EE_Registry::instance()->load_helper( 'URL' );
101
102
		$this->_tables = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Message' => new \...sp_message', 'MSG_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...
103
			'Message'=>new EE_Primary_Table('esp_message','MSG_ID')
104
		);
105
106
		$allowed_priority = array(
107
			self::priority_high => __( 'high', 'event_espresso' ),
108
			self::priority_medium => __( 'medium', 'event_espresso' ),
109
			self::priority_low => __( 'low', 'event_espresso' )
110
		);
111
112
		$this->_fields = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Message' => array...esso'), true, time()))) of type array<string,array<strin..._Datetime_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...
113
			'Message'=>array(
114
				'MSG_ID'=>new EE_Primary_Key_Int_Field('MSG_ID', __('Message ID','event_espresso')),
115
				'MSG_token' => new EE_Plain_Text_Field( 'MSG_token', __('Unique Token used to represent this row in publicly viewable contexts (eg. a url).', 'event_espresso' ), false, EEH_URL::generate_unique_token() ),
1 ignored issue
show
Documentation introduced by
\EEH_URL::generate_unique_token() is of type string, but the function expects a null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
116
				'GRP_ID'=>new EE_Foreign_Key_Int_Field( 'GRP_ID', __('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso' ), true, 0, 'Message_Template_Group' ),
117
				'TXN_ID' => new EE_Foreign_Key_Int_Field( 'TXN_ID', __( 'Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message', 'event_espresso' ), true, 0, 'Transaction' ),
118
				'MSG_messenger' => new EE_Plain_Text_Field('MSG_messenger', __( 'Corresponds to the EE_Messenger::name used to send this message. This will also be used to attempt any resending of the message.', 'event_espresso' ), false, 'email' ),
1 ignored issue
show
Documentation introduced by
'email' is of type string, but the function expects a null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
119
				'MSG_message_type' => new EE_Plain_Text_Field( 'MSG_message_type', __( 'Corresponds to the EE_message_type::name used to generate this message.', 'event_espresso' ), false, 'receipt' ),
1 ignored issue
show
Documentation introduced by
'receipt' is of type string, but the function expects a null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
				'MSG_context' => new EE_Plain_Text_Field( 'MSG_context', __( 'Context', 'event_espresso' ), false ),
121
				'MSG_recipient_ID' => new EE_Foreign_Key_Int_Field( 'MSG_recipient_ID', __( 'Recipient ID', 'event_espresso' ), true, null, array( 'Registration', 'Attendee', 'WP_User' ) ),
0 ignored issues
show
Documentation introduced by
array('Registration', 'Attendee', 'WP_User') is of type array<integer,string,{"0..."string","2":"string"}>, 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...
122
				'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field( 'MSG_recipient_type', __( 'Recipient Type', 'event_espresso' ), true, null, array( 'Registration', 'Attendee', 'WP_User' ) ),
0 ignored issues
show
Documentation introduced by
array('Registration', 'Attendee', 'WP_User') is of type array<integer,string,{"0..."string","2":"string"}>, 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...
123
				'MSG_content' => new EE_Maybe_Serialized_Text_Field( 'MSG_content', __( 'Content', 'event_espresso' ), true, '' ),
1 ignored issue
show
Documentation introduced by
'' is of type string, but the function expects a null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
124
				'MSG_to' => new EE_Maybe_Serialized_Text_Field( 'MSG_to', __( 'Address To', 'event_espresso' ), true ),
125
				'MSG_from' => new EE_Maybe_Serialized_Text_Field( 'MSG_from', __( 'Address From', 'event_espresso' ), true ),
126
				'MSG_subject' => new EE_Maybe_Serialized_Text_Field( 'MSG_subject', __( 'Subject', 'event_espresso' ), true, '' ),
1 ignored issue
show
Documentation introduced by
'' is of type string, but the function expects a null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
127
				'MSG_priority' => new EE_Enum_Integer_Field( 'MSG_priority', __( 'Priority', 'event_espresso' ), false, self::priority_low, $allowed_priority ),
128
				'STS_ID' => new EE_Foreign_Key_String_Field( 'STS_ID', __( 'Status', 'event_espresso' ), false, self::status_incomplete, 'Status' ),
129
				'MSG_created' => new EE_Datetime_Field( 'MSG_created', __( 'Created', 'event_espresso' ), false, time() ),
130
				'MSG_modified' => new EE_Datetime_Field( 'MSG_modified', __( 'Modified', 'event_espresso' ), true, time() )
131
			)
132
		);
133
		$this->_model_relations = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Attendee' => new ..._Belongs_To_Relation()) of type array<string,object<EE_B...Belongs_To_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...
134
			'Attendee' => new EE_Belongs_To_Any_Relation(),
135
			'Registration' => new EE_Belongs_To_Any_Relation(),
136
			'WP_User' => new EE_Belongs_To_Any_Relation(),
137
			'Message_Template_Group' => new EE_Belongs_To_Relation(),
138
			'Transaction' => new EE_Belongs_To_Relation()
139
		);
140
		parent::__construct( $timezone );
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 95 can also be of type string; however, EEM_Base::__construct() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
141
	}
142
143
144
145
	/**
146
	 * @return \EE_Message
147
	 */
148
	public function create_default_object() {
149
		/** @type EE_Message $message */
150
		$message = parent::create_default_object();
151
		return EE_Message_Factory::set_messenger_and_message_type( $message, false );
152
	}
153
154
155
156
	/**
157
	 * @param mixed $cols_n_values
158
	 * @return \EE_Message
159
	 */
160
	public function instantiate_class_from_array_or_object( $cols_n_values ) {
161
		/** @type EE_Message $message */
162
		$message = parent::instantiate_class_from_array_or_object( $cols_n_values );
163
		return EE_Message_Factory::set_messenger_and_message_type( $message );
164
	}
165
166
167
168
	/**
169
	 * Returns whether or not a message of that type was sent for a given attendee.
170
	 * @param EE_Attendee|int $attendee
171
	 * @param string $message_type the message type slug
172
	 * @return boolean
173
	 */
174 View Code Duplication
	public function message_sent_for_attendee( $attendee, $message_type ) {
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...
175
		$attendee_ID = EEM_Attendee::instance()->ensure_is_ID( $attendee );
176
		return $this->exists( array( array(
177
			'Attendee.ATT_ID' => $attendee_ID,
178
			'MSG_message_type' => $message_type,
179
			'STS_ID' => array( 'IN', $this->stati_indicating_sent() )
180
		) ) );
181
	}
182
183
184
185
186
	/**
187
	 * Returns whether or not a message of that type was sent for a given registration
188
	 * @param EE_Registration|int $registration
189
	 * @param string $message_type the message type slug
190
	 * @return boolean
191
	 */
192 View Code Duplication
	public function message_sent_for_registration( $registration, $message_type ) {
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...
193
		$registrationID = EEM_Registration::instance()->ensure_is_ID( $registration );
194
		return $this->exists( array( array(
195
			'Registration.REG_ID' => $registrationID,
196
			'MSG_message_type' => $message_type,
197
			'STS_ID' => array( 'IN', $this->stati_indicating_sent() )
198
		) ) );
199
	}
200
201
202
203
204
	/**
205
	 * This retrieves an EE_Message object from the db matching the given token string.
206
	 * @param string $token
207
	 * @return EE_Message | null
208
	 */
209
	public function get_one_by_token( $token ) {
210
		return $this->get_one( array( array(
211
			'MSG_token' => $token
212
		) ) );
213
	}
214
215
216
	/**
217
	 * Returns stati that indicate the message HAS been sent
218
	 * @return array of strings for possible stati
219
	 */
220
	public function stati_indicating_sent(){
221
		return apply_filters( 'FHEE__EEM_Message__stati_indicating_sent', array( self::status_sent ) );
222
	}
223
224
225
226
227
	/**
228
	 * Returns stati that indicate the message is waiting to be sent.
229
	 * @return array of strings for possible stati.
230
	 */
231
	public function stati_indicating_to_send() {
232
		return apply_filters( 'FHEE__EEM_Message__stati_indicating_to_send', array( self::status_idle, self::status_resend ) );
233
	}
234
235
236
237
	public function stati_indicating_failed_sending() {
238
		return apply_filters( 'FHEE__EEM_Message__stati_indicating_failed_sending', array( self::status_failed, self::status_retry ) );
239
	}
240
241
242
243
244
	/**
245
	 * Returns filterable array of all EEM_Message statuses.
246
	 * @return array
247
	 */
248
	public function all_statuses() {
249
		return apply_filters(
250
			'FHEE__EEM_Message__all_statuses',
251
			array(
252
				EEM_Message::status_sent,
253
				EEM_Message::status_incomplete,
254
				EEM_Message::status_idle,
255
				EEM_Message::status_resend,
256
				EEM_Message::status_retry,
257
				EEM_Message::status_failed,
258
			)
259
		);
260
	}
261
262
	/**
263
	 * Detects any specific query variables in the request and uses those to setup appropriate
264
	 * filter for any queries.
265
	 * @return array
266
	 */
267
	public function filter_by_query_params() {
268
		//expected possible query_vars, the key in this array matches an expected key in the request, the value, matches
269
		//the corresponding EEM_Base child reference.
270
		$expected_vars = array(
271
			'_REG_ID' => 'Registration',
272
			'ATT_ID' => 'Attendee',
273
			'ID' => 'WP_User',
274
			'TXN_ID' => 'Transaction',
275
			'EVT_ID' => 'Event',
276
		);
277
		$query_params[0] = array();
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...
278
		EE_Registry::instance()->load_class( 'Request_Handler' );
279
		foreach ( $expected_vars as $request_key => $model_name ) {
280
			if ( $request_value = EE_Registry::instance()->REQ->get( $request_key ) ) {
281
				//special case
282
				if ( $request_key === '_REG_ID' ) {
283
					$query_params[0]['AND**filter_by']['OR**filter_by'] = array(
284
						'Registration.REG_ID' => $request_value,
285
						'Attendee.Registration.REG_ID' => $request_value,
286
					);
287
					continue;
288
				}
289
				if ( $request_key === 'EVT_ID' ) {
290
					$query_params[0]['AND**filter_by']['OR**filter_by'] = array(
291
						'Registration.EVT_ID' => $request_value,
292
						'Attendee.Registration.EVT_ID' => $request_value,
293
					);
294
					continue;
295
				}
296
				$query_params[0][ $model_name . '.' . $request_key ] = EE_Registry::instance()->REQ->get( $request_key );
297
			}
298
		}
299
		return $query_params;
300
	}
301
302
303
}
304
// End of file EEM_Message.model.php
305
// Location: /includes/models/EEM_Message.model.php
306