Completed
Branch master (16095c)
by
unknown
09:17 queued 04:49
created
core/helpers/EEH_Inflector.helper.php 2 patches
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -33,384 +33,384 @@
 block discarded – undo
33 33
  */
34 34
 class EEH_Inflector
35 35
 {
36
-    // ------ CLASS METHODS ------ //
37
-    // ---- Public methods ---- //
38
-    // {{{ pluralize()
39
-
40
-    /**
41
-     * Just calls self::pluralize and strtolower on $word and returns it
42
-     * @param string $word
43
-     * @return string
44
-     */
45
-    public static function pluralize_and_lower($word)
46
-    {
47
-        return strtolower(self::pluralize($word));
48
-    }
49
-
50
-
51
-
52
-    /**
53
-     * @param string $word
54
-     * @return mixed
55
-     */
56
-    public static function singularize_and_upper($word)
57
-    {
58
-        return str_replace(' ', '_', self::humanize(self::singularize($word), 'all'));
59
-    }
60
-
61
-
62
-
63
-    /**
64
-     * Pluralizes English nouns.
65
-     *
66
-     * @access public
67
-     * @static
68
-     * @param    string    $word    English noun to pluralize
69
-     * @return string Plural noun
70
-     */
71
-    public static function pluralize($word)
72
-    {
73
-        $plural = array(
74
-            '/(quiz)$/i'               => '\1zes',
75
-            '/^(ox)$/i'                => '\1en',
76
-            '/([m|l])ouse$/i'          => '\1ice',
77
-            '/(matr|vert|ind)ix|ex$/i' => '\1ices',
78
-            '/(x|ch|ss|sh)$/i'         => '\1es',
79
-            '/([^aeiouy]|qu)ies$/i'    => '\1y',
80
-            '/([^aeiouy]|qu)y$/i'      => '\1ies',
81
-            '/(hive)$/i'               => '\1s',
82
-            '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
83
-            '/sis$/i'                  => 'ses',
84
-            '/([ti])um$/i'             => '\1a',
85
-            '/(buffal|tomat)o$/i'      => '\1oes',
86
-            '/(bu)s$/i'                => '\1ses',
87
-            '/(alias|status)/i'        => '\1es',
88
-            '/(octop|vir)us$/i'        => '\1i',
89
-            '/(ax|test)is$/i'          => '\1es',
90
-            '/s$/i'                    => 's',
91
-            '/$/'                      => 's');
92
-
93
-        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
94
-
95
-        $irregular = array(
96
-            'person' => 'people',
97
-            'man'    => 'men',
98
-            'child'  => 'children',
99
-            'sex'    => 'sexes',
100
-            'move'   => 'moves');
101
-
102
-        $lowercased_word = strtolower($word);
103
-
104
-        foreach ($uncountable as $_uncountable) {
105
-            if (
106
-                substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
107
-                    ! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])
108
-            ) {
109
-                return $word;
110
-            }
111
-        }
112
-
113
-        foreach ($irregular as $_plural => $_singular) {
114
-            if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
115
-                return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
116
-            }
117
-        }
118
-
119
-        foreach ($plural as $rule => $replacement) {
120
-            if (preg_match($rule, $word)) {
121
-                return preg_replace($rule, $replacement, $word);
122
-            }
123
-        }
124
-        return false;
125
-    }
126
-
127
-    // }}}
128
-    // {{{ singularize()
129
-
130
-    /**
131
-     * Singularizes English nouns.
132
-     *
133
-     * @access public
134
-     * @static
135
-     * @param    string    $word    English noun to singularize
136
-     * @return string Singular noun.
137
-     */
138
-    public static function singularize($word)
139
-    {
140
-        $singular = array(
141
-            '/(quiz)zes$/i'                                                    => '\1',
142
-            '/(matr)ices$/i'                                                   => '\1ix',
143
-            '/(vert|ind)ices$/i'                                               => '\1ex',
144
-            '/^(ox)en/i'                                                       => '\1',
145
-            '/(alias|status)es$/i'                                             => '\1',
146
-            '/([octop|vir])i$/i'                                               => '\1us',
147
-            '/(cris|ax|test)es$/i'                                             => '\1is',
148
-            '/(shoe)s$/i'                                                      => '\1',
149
-            '/(o)es$/i'                                                        => '\1',
150
-            '/(bus)es$/i'                                                      => '\1',
151
-            '/([m|l])ice$/i'                                                   => '\1ouse',
152
-            '/(x|ch|ss|sh)es$/i'                                               => '\1',
153
-            '/(m)ovies$/i'                                                     => '\1ovie',
154
-            '/(s)eries$/i'                                                     => '\1eries',
155
-            '/([^aeiouy]|qu)ies$/i'                                            => '\1y',
156
-            '/([lr])ves$/i'                                                    => '\1f',
157
-            '/(tive)s$/i'                                                      => '\1',
158
-            '/(hive)s$/i'                                                      => '\1',
159
-            '/([^f])ves$/i'                                                    => '\1fe',
160
-            '/(^analy)ses$/i'                                                  => '\1sis',
161
-            '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
162
-            '/([ti])a$/i'                                                      => '\1um',
163
-            '/(n)ews$/i'                                                       => '\1ews',
164
-            '/s$/i'                                                            => '',
165
-        );
166
-
167
-        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
168
-
169
-        $irregular = array(
170
-            'person' => 'people',
171
-            'man'    => 'men',
172
-            'child'  => 'children',
173
-            'sex'    => 'sexes',
174
-            'move'   => 'moves');
175
-
176
-        $lowercased_word = strtolower($word);
177
-        foreach ($uncountable as $_uncountable) {
178
-            if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
179
-                return $word;
180
-            }
181
-        }
182
-
183
-        foreach ($irregular as $_plural => $_singular) {
184
-            if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
185
-                return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
186
-            }
187
-        }
188
-
189
-        foreach ($singular as $rule => $replacement) {
190
-            if (preg_match($rule, $word)) {
191
-                return preg_replace($rule, $replacement, $word);
192
-            }
193
-        }
194
-
195
-        return $word;
196
-    }
197
-
198
-    // }}}
199
-    // {{{ titleize()
200
-
201
-    /**
202
-     * Converts an underscored or CamelCase word into a English
203
-     * sentence.
204
-     *
205
-     * The titleize static function converts text like "WelcomePage",
206
-     * "welcome_page" or  "welcome page" to this "Welcome
207
-     * Page".
208
-     * If second parameter is set to 'first' it will only
209
-     * capitalize the first character of the title.
210
-     *
211
-     * @access public
212
-     * @static
213
-     * @param    string    $word    Word to format as tile
214
-     * @param    string    $uppercase    If set to 'first' it will only uppercase the
215
-     * first character. Otherwise it will uppercase all
216
-     * the words in the title.
217
-     * @return string Text formatted as title
218
-     */
219
-    public static function titleize($word, $uppercase = '')
220
-    {
221
-        $uppercase = $uppercase === 'first' ? 'ucfirst' : 'ucwords';
222
-        return $uppercase(EEH_Inflector::humanize(EEH_Inflector::underscore($word)));
223
-    }
224
-
225
-    // }}}
226
-    // {{{ camelize()
227
-
228
-    /**
229
-     * Returns given word as CamelCased
230
-     *
231
-     * Converts a word like "send_email" to "SendEmail". It
232
-     * will remove non alphanumeric character from the word, so
233
-     * "who's online" will be converted to "WhoSOnline"
234
-     *
235
-     * @access public
236
-     * @static
237
-     * @see variablize
238
-     * @param    string    $word    Word to convert to camel case
239
-     * @return string UpperCamelCasedWord
240
-     */
241
-    public static function camelize($word)
242
-    {
243
-        return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word)));
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * Camelizes all but the first word. This is handy converting a method which followed EE4 legacy naming convention
250
-     * with the new PSR-based naming conventions
251
-     * @param $word
252
-     * @return string
253
-     */
254
-    public static function camelize_all_but_first($word)
255
-    {
256
-        return lcfirst(EEH_Inflector::camelize($word));
257
-    }
258
-    // }}}
259
-    // {{{ underscore()
260
-
261
-    /**
262
-     * Converts a word "into_it_s_underscored_version"
263
-     *
264
-     * Convert any "CamelCased" or "ordinary Word" into an
265
-     * "underscored_word".
266
-     *
267
-     * This can be really useful for creating friendly URLs.
268
-     *
269
-     * @access public
270
-     * @static
271
-     * @param    string    $word    Word to underscore
272
-     * @return string Underscored word
273
-     */
274
-    public static function underscore($word)
275
-    {
276
-        return strtolower(preg_replace('/[^A-Z^a-z^0-9]+/', '_', preg_replace('/([a-zd])([A-Z])/', '1_2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '1_2', $word))));
277
-    }
278
-
279
-    // }}}
280
-    // {{{ humanize()
281
-
282
-    /**
283
-     * Returns a human-readable string from $word
284
-     *
285
-     * Returns a human-readable string from $word, by replacing
286
-     * underscores with a space, and by upper-casing the initial
287
-     * character by default.
288
-     *
289
-     * If you need to uppercase all the words you just have to
290
-     * pass 'all' as a second parameter.
291
-     *
292
-     * @access public
293
-     * @static
294
-     * @param    string    $word    String to "humanize"
295
-     * @param    string    $uppercase    If set to 'all' it will uppercase all the words
296
-     * instead of just the first one.
297
-     * @return string Human-readable word
298
-     */
299
-    public static function humanize($word, $uppercase = '')
300
-    {
301
-        // make special exceptions for acronyms
302
-        $word = str_replace('wp_', 'WP_', $word);
303
-        $uppercase = $uppercase === 'all' ? 'ucwords' : 'ucfirst';
304
-        return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
305
-    }
306
-
307
-    // }}}
308
-    // {{{ variablize()
309
-
310
-    /**
311
-     * Same as camelize but first char is underscored
312
-     *
313
-     * Converts a word like "send_email" to "sendEmail". It
314
-     * will remove non alphanumeric character from the word, so
315
-     * "who's online" will be converted to "whoSOnline"
316
-     *
317
-     * @access public
318
-     * @static
319
-     * @see camelize
320
-     * @param    string    $word    Word to lowerCamelCase
321
-     * @return string Returns a lowerCamelCasedWord
322
-     */
323
-    public static function variablize($word)
324
-    {
325
-        $word = EEH_Inflector::camelize($word);
326
-        return strtolower($word[0]) . substr($word, 1);
327
-    }
328
-
329
-    // }}}
330
-    // {{{ tableize()
331
-
332
-    /**
333
-     * Converts a class name to its table name according to rails
334
-     * naming conventions.
335
-     *
336
-     * Converts "Person" to "people"
337
-     *
338
-     * @access public
339
-     * @static
340
-     * @see classify
341
-     * @param    string    $class_name    Class name for getting related table_name.
342
-     * @return string plural_table_name
343
-     */
344
-    public static function tableize($class_name)
345
-    {
346
-        return EEH_Inflector::pluralize(EEH_Inflector::underscore($class_name));
347
-    }
348
-
349
-    // }}}
350
-    // {{{ classify()
351
-
352
-    /**
353
-     * Converts a table name to its class name according to rails
354
-     * naming conventions.
355
-     *
356
-     * Converts "people" to "Person"
357
-     *
358
-     * @access public
359
-     * @static
360
-     * @see tableize
361
-     * @param    string    $table_name    Table name for getting related ClassName.
362
-     * @return string SingularClassName
363
-     */
364
-    public static function classify($table_name)
365
-    {
366
-        return EEH_Inflector::camelize(EEH_Inflector::singularize($table_name));
367
-    }
368
-
369
-    // }}}
370
-    // {{{ ordinalize()
371
-
372
-    /**
373
-     * Converts number to its ordinal English form.
374
-     *
375
-     * This method converts 13 to 13th, 2 to 2nd ...
376
-     *
377
-     * @access public
378
-     * @static
379
-     * @param    integer    $number    Number to get its ordinal value
380
-     * @return string Ordinal representation of given string.
381
-     */
382
-    public static function ordinalize($number)
383
-    {
384
-        if (in_array(($number % 100), range(11, 13))) {
385
-            return $number . 'th';
386
-        } else {
387
-            switch (($number % 10)) {
388
-                case 1:
389
-                    return $number . 'st';
390
-                    break;
391
-                case 2:
392
-                    return $number . 'nd';
393
-                    break;
394
-                case 3:
395
-                    return $number . 'rd';
396
-                default:
397
-                    return $number . 'th';
398
-                    break;
399
-            }
400
-        }
401
-    }
402
-
403
-
404
-
405
-    /**
406
-     * @param $string
407
-     * @return string
408
-     */
409
-    public static function add_indefinite_article($string)
410
-    {
411
-        if (strtolower($string) === 'null') {
412
-            return $string;
413
-        }
414
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
415
-    }
36
+	// ------ CLASS METHODS ------ //
37
+	// ---- Public methods ---- //
38
+	// {{{ pluralize()
39
+
40
+	/**
41
+	 * Just calls self::pluralize and strtolower on $word and returns it
42
+	 * @param string $word
43
+	 * @return string
44
+	 */
45
+	public static function pluralize_and_lower($word)
46
+	{
47
+		return strtolower(self::pluralize($word));
48
+	}
49
+
50
+
51
+
52
+	/**
53
+	 * @param string $word
54
+	 * @return mixed
55
+	 */
56
+	public static function singularize_and_upper($word)
57
+	{
58
+		return str_replace(' ', '_', self::humanize(self::singularize($word), 'all'));
59
+	}
60
+
61
+
62
+
63
+	/**
64
+	 * Pluralizes English nouns.
65
+	 *
66
+	 * @access public
67
+	 * @static
68
+	 * @param    string    $word    English noun to pluralize
69
+	 * @return string Plural noun
70
+	 */
71
+	public static function pluralize($word)
72
+	{
73
+		$plural = array(
74
+			'/(quiz)$/i'               => '\1zes',
75
+			'/^(ox)$/i'                => '\1en',
76
+			'/([m|l])ouse$/i'          => '\1ice',
77
+			'/(matr|vert|ind)ix|ex$/i' => '\1ices',
78
+			'/(x|ch|ss|sh)$/i'         => '\1es',
79
+			'/([^aeiouy]|qu)ies$/i'    => '\1y',
80
+			'/([^aeiouy]|qu)y$/i'      => '\1ies',
81
+			'/(hive)$/i'               => '\1s',
82
+			'/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
83
+			'/sis$/i'                  => 'ses',
84
+			'/([ti])um$/i'             => '\1a',
85
+			'/(buffal|tomat)o$/i'      => '\1oes',
86
+			'/(bu)s$/i'                => '\1ses',
87
+			'/(alias|status)/i'        => '\1es',
88
+			'/(octop|vir)us$/i'        => '\1i',
89
+			'/(ax|test)is$/i'          => '\1es',
90
+			'/s$/i'                    => 's',
91
+			'/$/'                      => 's');
92
+
93
+		$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
94
+
95
+		$irregular = array(
96
+			'person' => 'people',
97
+			'man'    => 'men',
98
+			'child'  => 'children',
99
+			'sex'    => 'sexes',
100
+			'move'   => 'moves');
101
+
102
+		$lowercased_word = strtolower($word);
103
+
104
+		foreach ($uncountable as $_uncountable) {
105
+			if (
106
+				substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
107
+					! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])
108
+			) {
109
+				return $word;
110
+			}
111
+		}
112
+
113
+		foreach ($irregular as $_plural => $_singular) {
114
+			if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
115
+				return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
116
+			}
117
+		}
118
+
119
+		foreach ($plural as $rule => $replacement) {
120
+			if (preg_match($rule, $word)) {
121
+				return preg_replace($rule, $replacement, $word);
122
+			}
123
+		}
124
+		return false;
125
+	}
126
+
127
+	// }}}
128
+	// {{{ singularize()
129
+
130
+	/**
131
+	 * Singularizes English nouns.
132
+	 *
133
+	 * @access public
134
+	 * @static
135
+	 * @param    string    $word    English noun to singularize
136
+	 * @return string Singular noun.
137
+	 */
138
+	public static function singularize($word)
139
+	{
140
+		$singular = array(
141
+			'/(quiz)zes$/i'                                                    => '\1',
142
+			'/(matr)ices$/i'                                                   => '\1ix',
143
+			'/(vert|ind)ices$/i'                                               => '\1ex',
144
+			'/^(ox)en/i'                                                       => '\1',
145
+			'/(alias|status)es$/i'                                             => '\1',
146
+			'/([octop|vir])i$/i'                                               => '\1us',
147
+			'/(cris|ax|test)es$/i'                                             => '\1is',
148
+			'/(shoe)s$/i'                                                      => '\1',
149
+			'/(o)es$/i'                                                        => '\1',
150
+			'/(bus)es$/i'                                                      => '\1',
151
+			'/([m|l])ice$/i'                                                   => '\1ouse',
152
+			'/(x|ch|ss|sh)es$/i'                                               => '\1',
153
+			'/(m)ovies$/i'                                                     => '\1ovie',
154
+			'/(s)eries$/i'                                                     => '\1eries',
155
+			'/([^aeiouy]|qu)ies$/i'                                            => '\1y',
156
+			'/([lr])ves$/i'                                                    => '\1f',
157
+			'/(tive)s$/i'                                                      => '\1',
158
+			'/(hive)s$/i'                                                      => '\1',
159
+			'/([^f])ves$/i'                                                    => '\1fe',
160
+			'/(^analy)ses$/i'                                                  => '\1sis',
161
+			'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
162
+			'/([ti])a$/i'                                                      => '\1um',
163
+			'/(n)ews$/i'                                                       => '\1ews',
164
+			'/s$/i'                                                            => '',
165
+		);
166
+
167
+		$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
168
+
169
+		$irregular = array(
170
+			'person' => 'people',
171
+			'man'    => 'men',
172
+			'child'  => 'children',
173
+			'sex'    => 'sexes',
174
+			'move'   => 'moves');
175
+
176
+		$lowercased_word = strtolower($word);
177
+		foreach ($uncountable as $_uncountable) {
178
+			if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
179
+				return $word;
180
+			}
181
+		}
182
+
183
+		foreach ($irregular as $_plural => $_singular) {
184
+			if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
185
+				return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
186
+			}
187
+		}
188
+
189
+		foreach ($singular as $rule => $replacement) {
190
+			if (preg_match($rule, $word)) {
191
+				return preg_replace($rule, $replacement, $word);
192
+			}
193
+		}
194
+
195
+		return $word;
196
+	}
197
+
198
+	// }}}
199
+	// {{{ titleize()
200
+
201
+	/**
202
+	 * Converts an underscored or CamelCase word into a English
203
+	 * sentence.
204
+	 *
205
+	 * The titleize static function converts text like "WelcomePage",
206
+	 * "welcome_page" or  "welcome page" to this "Welcome
207
+	 * Page".
208
+	 * If second parameter is set to 'first' it will only
209
+	 * capitalize the first character of the title.
210
+	 *
211
+	 * @access public
212
+	 * @static
213
+	 * @param    string    $word    Word to format as tile
214
+	 * @param    string    $uppercase    If set to 'first' it will only uppercase the
215
+	 * first character. Otherwise it will uppercase all
216
+	 * the words in the title.
217
+	 * @return string Text formatted as title
218
+	 */
219
+	public static function titleize($word, $uppercase = '')
220
+	{
221
+		$uppercase = $uppercase === 'first' ? 'ucfirst' : 'ucwords';
222
+		return $uppercase(EEH_Inflector::humanize(EEH_Inflector::underscore($word)));
223
+	}
224
+
225
+	// }}}
226
+	// {{{ camelize()
227
+
228
+	/**
229
+	 * Returns given word as CamelCased
230
+	 *
231
+	 * Converts a word like "send_email" to "SendEmail". It
232
+	 * will remove non alphanumeric character from the word, so
233
+	 * "who's online" will be converted to "WhoSOnline"
234
+	 *
235
+	 * @access public
236
+	 * @static
237
+	 * @see variablize
238
+	 * @param    string    $word    Word to convert to camel case
239
+	 * @return string UpperCamelCasedWord
240
+	 */
241
+	public static function camelize($word)
242
+	{
243
+		return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word)));
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * Camelizes all but the first word. This is handy converting a method which followed EE4 legacy naming convention
250
+	 * with the new PSR-based naming conventions
251
+	 * @param $word
252
+	 * @return string
253
+	 */
254
+	public static function camelize_all_but_first($word)
255
+	{
256
+		return lcfirst(EEH_Inflector::camelize($word));
257
+	}
258
+	// }}}
259
+	// {{{ underscore()
260
+
261
+	/**
262
+	 * Converts a word "into_it_s_underscored_version"
263
+	 *
264
+	 * Convert any "CamelCased" or "ordinary Word" into an
265
+	 * "underscored_word".
266
+	 *
267
+	 * This can be really useful for creating friendly URLs.
268
+	 *
269
+	 * @access public
270
+	 * @static
271
+	 * @param    string    $word    Word to underscore
272
+	 * @return string Underscored word
273
+	 */
274
+	public static function underscore($word)
275
+	{
276
+		return strtolower(preg_replace('/[^A-Z^a-z^0-9]+/', '_', preg_replace('/([a-zd])([A-Z])/', '1_2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '1_2', $word))));
277
+	}
278
+
279
+	// }}}
280
+	// {{{ humanize()
281
+
282
+	/**
283
+	 * Returns a human-readable string from $word
284
+	 *
285
+	 * Returns a human-readable string from $word, by replacing
286
+	 * underscores with a space, and by upper-casing the initial
287
+	 * character by default.
288
+	 *
289
+	 * If you need to uppercase all the words you just have to
290
+	 * pass 'all' as a second parameter.
291
+	 *
292
+	 * @access public
293
+	 * @static
294
+	 * @param    string    $word    String to "humanize"
295
+	 * @param    string    $uppercase    If set to 'all' it will uppercase all the words
296
+	 * instead of just the first one.
297
+	 * @return string Human-readable word
298
+	 */
299
+	public static function humanize($word, $uppercase = '')
300
+	{
301
+		// make special exceptions for acronyms
302
+		$word = str_replace('wp_', 'WP_', $word);
303
+		$uppercase = $uppercase === 'all' ? 'ucwords' : 'ucfirst';
304
+		return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
305
+	}
306
+
307
+	// }}}
308
+	// {{{ variablize()
309
+
310
+	/**
311
+	 * Same as camelize but first char is underscored
312
+	 *
313
+	 * Converts a word like "send_email" to "sendEmail". It
314
+	 * will remove non alphanumeric character from the word, so
315
+	 * "who's online" will be converted to "whoSOnline"
316
+	 *
317
+	 * @access public
318
+	 * @static
319
+	 * @see camelize
320
+	 * @param    string    $word    Word to lowerCamelCase
321
+	 * @return string Returns a lowerCamelCasedWord
322
+	 */
323
+	public static function variablize($word)
324
+	{
325
+		$word = EEH_Inflector::camelize($word);
326
+		return strtolower($word[0]) . substr($word, 1);
327
+	}
328
+
329
+	// }}}
330
+	// {{{ tableize()
331
+
332
+	/**
333
+	 * Converts a class name to its table name according to rails
334
+	 * naming conventions.
335
+	 *
336
+	 * Converts "Person" to "people"
337
+	 *
338
+	 * @access public
339
+	 * @static
340
+	 * @see classify
341
+	 * @param    string    $class_name    Class name for getting related table_name.
342
+	 * @return string plural_table_name
343
+	 */
344
+	public static function tableize($class_name)
345
+	{
346
+		return EEH_Inflector::pluralize(EEH_Inflector::underscore($class_name));
347
+	}
348
+
349
+	// }}}
350
+	// {{{ classify()
351
+
352
+	/**
353
+	 * Converts a table name to its class name according to rails
354
+	 * naming conventions.
355
+	 *
356
+	 * Converts "people" to "Person"
357
+	 *
358
+	 * @access public
359
+	 * @static
360
+	 * @see tableize
361
+	 * @param    string    $table_name    Table name for getting related ClassName.
362
+	 * @return string SingularClassName
363
+	 */
364
+	public static function classify($table_name)
365
+	{
366
+		return EEH_Inflector::camelize(EEH_Inflector::singularize($table_name));
367
+	}
368
+
369
+	// }}}
370
+	// {{{ ordinalize()
371
+
372
+	/**
373
+	 * Converts number to its ordinal English form.
374
+	 *
375
+	 * This method converts 13 to 13th, 2 to 2nd ...
376
+	 *
377
+	 * @access public
378
+	 * @static
379
+	 * @param    integer    $number    Number to get its ordinal value
380
+	 * @return string Ordinal representation of given string.
381
+	 */
382
+	public static function ordinalize($number)
383
+	{
384
+		if (in_array(($number % 100), range(11, 13))) {
385
+			return $number . 'th';
386
+		} else {
387
+			switch (($number % 10)) {
388
+				case 1:
389
+					return $number . 'st';
390
+					break;
391
+				case 2:
392
+					return $number . 'nd';
393
+					break;
394
+				case 3:
395
+					return $number . 'rd';
396
+				default:
397
+					return $number . 'th';
398
+					break;
399
+			}
400
+		}
401
+	}
402
+
403
+
404
+
405
+	/**
406
+	 * @param $string
407
+	 * @return string
408
+	 */
409
+	public static function add_indefinite_article($string)
410
+	{
411
+		if (strtolower($string) === 'null') {
412
+			return $string;
413
+		}
414
+		return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
415
+	}
416 416
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -104,15 +104,15 @@  discard block
 block discarded – undo
104 104
         foreach ($uncountable as $_uncountable) {
105 105
             if (
106 106
                 substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
107
-                    ! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])
107
+                    ! ctype_alpha($lowercased_word[strlen($lowercased_word) - strlen($_uncountable)])
108 108
             ) {
109 109
                 return $word;
110 110
             }
111 111
         }
112 112
 
113 113
         foreach ($irregular as $_plural => $_singular) {
114
-            if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
115
-                return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
114
+            if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
115
+                return preg_replace('/('.$_plural.')$/i', substr($arr[0], 0, 1).substr($_singular, 1), $word);
116 116
             }
117 117
         }
118 118
 
@@ -181,8 +181,8 @@  discard block
 block discarded – undo
181 181
         }
182 182
 
183 183
         foreach ($irregular as $_plural => $_singular) {
184
-            if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
185
-                return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
184
+            if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
185
+                return preg_replace('/('.$_singular.')$/i', substr($arr[0], 0, 1).substr($_plural, 1), $word);
186 186
             }
187 187
         }
188 188
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
     public static function variablize($word)
324 324
     {
325 325
         $word = EEH_Inflector::camelize($word);
326
-        return strtolower($word[0]) . substr($word, 1);
326
+        return strtolower($word[0]).substr($word, 1);
327 327
     }
328 328
 
329 329
     // }}}
@@ -382,19 +382,19 @@  discard block
 block discarded – undo
382 382
     public static function ordinalize($number)
383 383
     {
384 384
         if (in_array(($number % 100), range(11, 13))) {
385
-            return $number . 'th';
385
+            return $number.'th';
386 386
         } else {
387 387
             switch (($number % 10)) {
388 388
                 case 1:
389
-                    return $number . 'st';
389
+                    return $number.'st';
390 390
                     break;
391 391
                 case 2:
392
-                    return $number . 'nd';
392
+                    return $number.'nd';
393 393
                     break;
394 394
                 case 3:
395
-                    return $number . 'rd';
395
+                    return $number.'rd';
396 396
                 default:
397
-                    return $number . 'th';
397
+                    return $number.'th';
398 398
                     break;
399 399
             }
400 400
         }
@@ -411,6 +411,6 @@  discard block
 block discarded – undo
411 411
         if (strtolower($string) === 'null') {
412 412
             return $string;
413 413
         }
414
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
414
+        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ').$string;
415 415
     }
416 416
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Parse_Shortcodes.helper.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -208,14 +208,14 @@  discard block
 block discarded – undo
208 208
                 if ($sc_obj instanceof EE_Shortcodes) {
209 209
                     // we need to setup any dynamic shortcodes so that they work with the array_key_exists
210 210
                     preg_match_all('/(\[[A-Za-z0-9\_]+_\*)/', $shortcode, $matches);
211
-                    $sc_to_verify = ! empty($matches[0]) ? $matches[0][0] . ']' : $shortcode;
211
+                    $sc_to_verify = ! empty($matches[0]) ? $matches[0][0].']' : $shortcode;
212 212
 
213
-                    if (! array_key_exists($sc_to_verify, $sc_obj->get_shortcodes())) {
213
+                    if ( ! array_key_exists($sc_to_verify, $sc_obj->get_shortcodes())) {
214 214
                         continue; // the given shortcode isn't in this object
215 215
                     }
216 216
 
217 217
                     // if this isn't  a "list" type shortcode then we'll send along the data vanilla instead of in an array.
218
-                    if (! in_array($sc_to_verify, $list_type_shortcodes)) {
218
+                    if ( ! in_array($sc_to_verify, $list_type_shortcodes)) {
219 219
                         $data_send = ! is_object($this->_data) && isset($this->_data['data']) ? $this->_data['data'] : $this->_data;
220 220
                     } else {
221 221
                         $data_send = $this->_data;
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
         foreach ($valid_shortcodes as $shortcode_ref) {
272 272
             $ref       = ucwords(str_replace('_', ' ', $shortcode_ref));
273 273
             $ref       = str_replace(' ', '_', $ref);
274
-            $classname = 'EE_' . $ref . '_Shortcodes';
274
+            $classname = 'EE_'.$ref.'_Shortcodes';
275 275
             if (class_exists($classname)) {
276 276
                 $this->_shortcode_objs[] = new $classname();
277 277
             }
Please login to merge, or discard this patch.
Indentation   +264 added lines, -264 removed lines patch added patch discarded remove patch
@@ -11,268 +11,268 @@
 block discarded – undo
11 11
  */
12 12
 class EEH_Parse_Shortcodes
13 13
 {
14
-    /**
15
-     * holds the template
16
-     *
17
-     * @access private
18
-     * @var mixed (string|array)
19
-     */
20
-    private $_template;
21
-
22
-
23
-    /**
24
-     * holds the incoming data object
25
-     *
26
-     * @access private
27
-     * @var object
28
-     */
29
-    private $_data;
30
-
31
-
32
-    /**
33
-     * will hold an array of EE_Shortcodes library objects.
34
-     *
35
-     * @access private
36
-     * @var EE_Shortcodes[]
37
-     */
38
-    private $_shortcode_objs = array();
39
-
40
-
41
-    public function __construct()
42
-    {
43
-    }
44
-
45
-
46
-    /**
47
-     * This kicks off the parsing of shortcodes in message templates
48
-     *
49
-     * @param  string                $template         This is the incoming string to be parsed
50
-     * @param  EE_Messages_Addressee $data             This is the incoming data object
51
-     * @param  array                 $valid_shortcodes An array of strings that correspond to EE_Shortcode libraries
52
-     * @param EE_message_type        $message_type     The message type that called the parser
53
-     * @param EE_messenger           $messenger        The active messenger for this parsing session.
54
-     * @param EE_Message             $message
55
-     * @return string                   The parsed template string
56
-     */
57
-    public function parse_message_template(
58
-        $template,
59
-        EE_Messages_Addressee $data,
60
-        $valid_shortcodes,
61
-        EE_message_type $message_type,
62
-        EE_messenger $messenger,
63
-        EE_Message $message
64
-    ) {
65
-        $extra_data = array(
66
-            'messenger'    => $messenger,
67
-            'message_type' => $message_type,
68
-            'message'      => $message,
69
-        );
70
-        $this->_init_data($template, $data, $valid_shortcodes, $extra_data);
71
-        $this->_template = is_array($template) ? $template['main'] : $template;
72
-        return $this->_parse_message_template();
73
-    }
74
-
75
-
76
-    public function parse_attendee_list_template(
77
-        $template,
78
-        EE_Registration $registration,
79
-        $valid_shortcodes,
80
-        $extra_data = array()
81
-    ) {
82
-        $this->_init_data($template, $registration, $valid_shortcodes, $extra_data);
83
-        $this->_template = is_array($template) ? $template['attendee_list'] : $template;
84
-        return $this->_parse_message_template();
85
-    }
86
-
87
-    public function parse_event_list_template($template, EE_Event $event, $valid_shortcodes, $extra_data = array())
88
-    {
89
-        $this->_init_data($template, $event, $valid_shortcodes, $extra_data);
90
-        $this->_template = is_array($template) ? $template['event_list'] : $template;
91
-        return $this->_parse_message_template();
92
-    }
93
-
94
-
95
-    public function parse_ticket_list_template($template, EE_Ticket $ticket, $valid_shortcodes, $extra_data = array())
96
-    {
97
-        $this->_init_data($template, $ticket, $valid_shortcodes, $extra_data);
98
-        $this->_template = is_array($template) ? $template['ticket_list'] : $template;
99
-        return $this->_parse_message_template();
100
-    }
101
-
102
-
103
-    public function parse_line_item_list_template(
104
-        $template,
105
-        EE_Line_Item $line_item,
106
-        $valid_shortcodes,
107
-        $extra_data = array()
108
-    ) {
109
-        $this->_init_data($template, $line_item, $valid_shortcodes, $extra_data);
110
-        $this->_template = is_array($template) ? $template['ticket_line_item_no_pms'] : $template;
111
-        return $this->_parse_message_template();
112
-    }
113
-
114
-
115
-    public function parse_payment_list_template(
116
-        $template,
117
-        EE_Payment $payment_item,
118
-        $valid_shortcodes,
119
-        $extra_data = array()
120
-    ) {
121
-        $this->_init_data($template, $payment_item, $valid_shortcodes, $extra_data);
122
-        $this->_template = is_array($template) ? $template['payment_list'] : $template;
123
-        return $this->_parse_message_template();
124
-    }
125
-
126
-
127
-    public function parse_datetime_list_template(
128
-        $template,
129
-        EE_Datetime $datetime,
130
-        $valid_shortcodes,
131
-        $extra_data = array()
132
-    ) {
133
-        $this->_init_data($template, $datetime, $valid_shortcodes, $extra_data);
134
-        $this->_template = is_array($template) ? $template['datetime_list'] : $template;
135
-        return $this->_parse_message_template();
136
-    }
137
-
138
-
139
-    public function parse_question_list_template($template, EE_Answer $answer, $valid_shortcodes, $extra_data = array())
140
-    {
141
-        $this->_init_data($template, $answer, $valid_shortcodes, $extra_data);
142
-        $this->_template = is_array($template) ? $template['question_list'] : $template;
143
-        return $this->_parse_message_template();
144
-    }
145
-
146
-
147
-    private function _init_data($template, $data, $valid_shortcodes, $extra_data = array())
148
-    {
149
-        $this->_reset_props();
150
-        $this->_data['template']   = $template;
151
-        $this->_data['data']       = $data;
152
-        $this->_data['extra_data'] = $extra_data;
153
-        $this->_set_shortcodes($valid_shortcodes);
154
-    }
155
-
156
-
157
-    private function _reset_props()
158
-    {
159
-        $this->_template       = $this->_data = null;
160
-        $this->_shortcode_objs = array();
161
-    }
162
-
163
-
164
-    /**
165
-     * takes the given template and parses it with the $_shortcodes property
166
-     *
167
-     * @access private
168
-     * @return string
169
-     */
170
-    private function _parse_message_template()
171
-    {
172
-        // now let's get a list of shortcodes that are found in the given template
173
-        preg_match_all('/(\[.+?\])/', $this->_template, $matches);
174
-        $shortcodes = (array) $matches[0]; // this should be an array of shortcodes in the template string.
175
-
176
-        $matched_code = array();
177
-        $sc_values    = array();
178
-
179
-        $list_type_shortcodes = array(
180
-            '[ATTENDEE_LIST]',
181
-            '[EVENT_LIST]',
182
-            '[TICKET_LIST]',
183
-            '[DATETIME_LIST]',
184
-            '[QUESTION_LIST]',
185
-            '[RECIPIENT_QUESTION_LIST]',
186
-            '[PRIMARY_REGISTRANT_QUESTION_LIST]',
187
-            '[RECIPIENT_TICKET_LIST]',
188
-            '[PRIMARY_REGISTRANT_TICKET_LIST]',
189
-            '[RECIPIENT_DATETIME_LIST]',
190
-            '[PRIMARY_REGISTRANT_DATETIME_LIST]',
191
-            '[TICKET_LINE_ITEM_LIST]',
192
-            '[TAX_LINE_ITEM_LIST]',
193
-            '[ADDITIONAL_LINE_ITEM_LIST]',
194
-            '[PRICE_MODIFIER_LINE_ITEM_LIST]',
195
-            '[PAYMENT_LIST_*]',
196
-        );
197
-
198
-        $list_type_shortcodes = apply_filters(
199
-            'FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes',
200
-            $list_type_shortcodes
201
-        );
202
-
203
-        // now lets go ahead and loop through our parsers for each shortcode and setup the values
204
-        foreach ($shortcodes as $shortcode) {
205
-            foreach ($this->_shortcode_objs as $sc_obj) {
206
-                if ($sc_obj instanceof EE_Shortcodes) {
207
-                    // we need to setup any dynamic shortcodes so that they work with the array_key_exists
208
-                    preg_match_all('/(\[[A-Za-z0-9\_]+_\*)/', $shortcode, $matches);
209
-                    $sc_to_verify = ! empty($matches[0]) ? $matches[0][0] . ']' : $shortcode;
210
-
211
-                    if (! array_key_exists($sc_to_verify, $sc_obj->get_shortcodes())) {
212
-                        continue; // the given shortcode isn't in this object
213
-                    }
214
-
215
-                    // if this isn't  a "list" type shortcode then we'll send along the data vanilla instead of in an array.
216
-                    if (! in_array($sc_to_verify, $list_type_shortcodes)) {
217
-                        $data_send = ! is_object($this->_data) && isset($this->_data['data']) ? $this->_data['data'] : $this->_data;
218
-                    } else {
219
-                        $data_send = $this->_data;
220
-                    }
221
-
222
-                    // is this a conditional type shortcode?  If it is then we actually parse the template here.
223
-                    if ($this->_is_conditional_shortcode($shortcode)) {
224
-                        // most shortcode parsers are not going to have a match for this shortcode and will return an
225
-                        // empty string so we need to make sure that we're only replacing the template when there is a non empty string.
226
-                        $parsed = $sc_obj->parser($shortcode, $data_send, $this->_data['extra_data']);
227
-                        if ($parsed) {
228
-                            $this->_template = $parsed;
229
-                        }
230
-                    }
231
-
232
-                    $parsed = $sc_obj->parser($shortcode, $data_send, $this->_data['extra_data']);
233
-
234
-                    $matched_code[] = $shortcode;
235
-                    $sc_values[]    = $parsed;
236
-                }
237
-            }
238
-        }
239
-
240
-        // now we've got parsed values for all the shortcodes in the template so we can go ahead and swap the shortcodes out.
241
-        $parsed = str_replace(array_values($matched_code), array_values($sc_values), $this->_template);
242
-        return $parsed;
243
-    }
244
-
245
-
246
-    /**
247
-     * Simply returns whether the given shortcode matches the structure for a conditional shortcode.
248
-     *
249
-     * Does it match this format: `[IF_`
250
-     *
251
-     * @param $shortcode
252
-     */
253
-    protected function _is_conditional_shortcode($shortcode)
254
-    {
255
-        return strpos($shortcode, '[IF_') === 0;
256
-    }
257
-
258
-
259
-    /**
260
-     * This sets the shortcodes property from the incoming array of valid shortcodes that corresponds to names of
261
-     * various EE_Shortcode library objects
262
-     *
263
-     * @access private
264
-     * @param array $valid_shortcodes an array of strings corresponding to EE_Shortcode Library objects
265
-     * @return void
266
-     */
267
-    private function _set_shortcodes($valid_shortcodes)
268
-    {
269
-        foreach ($valid_shortcodes as $shortcode_ref) {
270
-            $ref       = ucwords(str_replace('_', ' ', $shortcode_ref));
271
-            $ref       = str_replace(' ', '_', $ref);
272
-            $classname = 'EE_' . $ref . '_Shortcodes';
273
-            if (class_exists($classname)) {
274
-                $this->_shortcode_objs[] = new $classname();
275
-            }
276
-        }
277
-    }
14
+	/**
15
+	 * holds the template
16
+	 *
17
+	 * @access private
18
+	 * @var mixed (string|array)
19
+	 */
20
+	private $_template;
21
+
22
+
23
+	/**
24
+	 * holds the incoming data object
25
+	 *
26
+	 * @access private
27
+	 * @var object
28
+	 */
29
+	private $_data;
30
+
31
+
32
+	/**
33
+	 * will hold an array of EE_Shortcodes library objects.
34
+	 *
35
+	 * @access private
36
+	 * @var EE_Shortcodes[]
37
+	 */
38
+	private $_shortcode_objs = array();
39
+
40
+
41
+	public function __construct()
42
+	{
43
+	}
44
+
45
+
46
+	/**
47
+	 * This kicks off the parsing of shortcodes in message templates
48
+	 *
49
+	 * @param  string                $template         This is the incoming string to be parsed
50
+	 * @param  EE_Messages_Addressee $data             This is the incoming data object
51
+	 * @param  array                 $valid_shortcodes An array of strings that correspond to EE_Shortcode libraries
52
+	 * @param EE_message_type        $message_type     The message type that called the parser
53
+	 * @param EE_messenger           $messenger        The active messenger for this parsing session.
54
+	 * @param EE_Message             $message
55
+	 * @return string                   The parsed template string
56
+	 */
57
+	public function parse_message_template(
58
+		$template,
59
+		EE_Messages_Addressee $data,
60
+		$valid_shortcodes,
61
+		EE_message_type $message_type,
62
+		EE_messenger $messenger,
63
+		EE_Message $message
64
+	) {
65
+		$extra_data = array(
66
+			'messenger'    => $messenger,
67
+			'message_type' => $message_type,
68
+			'message'      => $message,
69
+		);
70
+		$this->_init_data($template, $data, $valid_shortcodes, $extra_data);
71
+		$this->_template = is_array($template) ? $template['main'] : $template;
72
+		return $this->_parse_message_template();
73
+	}
74
+
75
+
76
+	public function parse_attendee_list_template(
77
+		$template,
78
+		EE_Registration $registration,
79
+		$valid_shortcodes,
80
+		$extra_data = array()
81
+	) {
82
+		$this->_init_data($template, $registration, $valid_shortcodes, $extra_data);
83
+		$this->_template = is_array($template) ? $template['attendee_list'] : $template;
84
+		return $this->_parse_message_template();
85
+	}
86
+
87
+	public function parse_event_list_template($template, EE_Event $event, $valid_shortcodes, $extra_data = array())
88
+	{
89
+		$this->_init_data($template, $event, $valid_shortcodes, $extra_data);
90
+		$this->_template = is_array($template) ? $template['event_list'] : $template;
91
+		return $this->_parse_message_template();
92
+	}
93
+
94
+
95
+	public function parse_ticket_list_template($template, EE_Ticket $ticket, $valid_shortcodes, $extra_data = array())
96
+	{
97
+		$this->_init_data($template, $ticket, $valid_shortcodes, $extra_data);
98
+		$this->_template = is_array($template) ? $template['ticket_list'] : $template;
99
+		return $this->_parse_message_template();
100
+	}
101
+
102
+
103
+	public function parse_line_item_list_template(
104
+		$template,
105
+		EE_Line_Item $line_item,
106
+		$valid_shortcodes,
107
+		$extra_data = array()
108
+	) {
109
+		$this->_init_data($template, $line_item, $valid_shortcodes, $extra_data);
110
+		$this->_template = is_array($template) ? $template['ticket_line_item_no_pms'] : $template;
111
+		return $this->_parse_message_template();
112
+	}
113
+
114
+
115
+	public function parse_payment_list_template(
116
+		$template,
117
+		EE_Payment $payment_item,
118
+		$valid_shortcodes,
119
+		$extra_data = array()
120
+	) {
121
+		$this->_init_data($template, $payment_item, $valid_shortcodes, $extra_data);
122
+		$this->_template = is_array($template) ? $template['payment_list'] : $template;
123
+		return $this->_parse_message_template();
124
+	}
125
+
126
+
127
+	public function parse_datetime_list_template(
128
+		$template,
129
+		EE_Datetime $datetime,
130
+		$valid_shortcodes,
131
+		$extra_data = array()
132
+	) {
133
+		$this->_init_data($template, $datetime, $valid_shortcodes, $extra_data);
134
+		$this->_template = is_array($template) ? $template['datetime_list'] : $template;
135
+		return $this->_parse_message_template();
136
+	}
137
+
138
+
139
+	public function parse_question_list_template($template, EE_Answer $answer, $valid_shortcodes, $extra_data = array())
140
+	{
141
+		$this->_init_data($template, $answer, $valid_shortcodes, $extra_data);
142
+		$this->_template = is_array($template) ? $template['question_list'] : $template;
143
+		return $this->_parse_message_template();
144
+	}
145
+
146
+
147
+	private function _init_data($template, $data, $valid_shortcodes, $extra_data = array())
148
+	{
149
+		$this->_reset_props();
150
+		$this->_data['template']   = $template;
151
+		$this->_data['data']       = $data;
152
+		$this->_data['extra_data'] = $extra_data;
153
+		$this->_set_shortcodes($valid_shortcodes);
154
+	}
155
+
156
+
157
+	private function _reset_props()
158
+	{
159
+		$this->_template       = $this->_data = null;
160
+		$this->_shortcode_objs = array();
161
+	}
162
+
163
+
164
+	/**
165
+	 * takes the given template and parses it with the $_shortcodes property
166
+	 *
167
+	 * @access private
168
+	 * @return string
169
+	 */
170
+	private function _parse_message_template()
171
+	{
172
+		// now let's get a list of shortcodes that are found in the given template
173
+		preg_match_all('/(\[.+?\])/', $this->_template, $matches);
174
+		$shortcodes = (array) $matches[0]; // this should be an array of shortcodes in the template string.
175
+
176
+		$matched_code = array();
177
+		$sc_values    = array();
178
+
179
+		$list_type_shortcodes = array(
180
+			'[ATTENDEE_LIST]',
181
+			'[EVENT_LIST]',
182
+			'[TICKET_LIST]',
183
+			'[DATETIME_LIST]',
184
+			'[QUESTION_LIST]',
185
+			'[RECIPIENT_QUESTION_LIST]',
186
+			'[PRIMARY_REGISTRANT_QUESTION_LIST]',
187
+			'[RECIPIENT_TICKET_LIST]',
188
+			'[PRIMARY_REGISTRANT_TICKET_LIST]',
189
+			'[RECIPIENT_DATETIME_LIST]',
190
+			'[PRIMARY_REGISTRANT_DATETIME_LIST]',
191
+			'[TICKET_LINE_ITEM_LIST]',
192
+			'[TAX_LINE_ITEM_LIST]',
193
+			'[ADDITIONAL_LINE_ITEM_LIST]',
194
+			'[PRICE_MODIFIER_LINE_ITEM_LIST]',
195
+			'[PAYMENT_LIST_*]',
196
+		);
197
+
198
+		$list_type_shortcodes = apply_filters(
199
+			'FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes',
200
+			$list_type_shortcodes
201
+		);
202
+
203
+		// now lets go ahead and loop through our parsers for each shortcode and setup the values
204
+		foreach ($shortcodes as $shortcode) {
205
+			foreach ($this->_shortcode_objs as $sc_obj) {
206
+				if ($sc_obj instanceof EE_Shortcodes) {
207
+					// we need to setup any dynamic shortcodes so that they work with the array_key_exists
208
+					preg_match_all('/(\[[A-Za-z0-9\_]+_\*)/', $shortcode, $matches);
209
+					$sc_to_verify = ! empty($matches[0]) ? $matches[0][0] . ']' : $shortcode;
210
+
211
+					if (! array_key_exists($sc_to_verify, $sc_obj->get_shortcodes())) {
212
+						continue; // the given shortcode isn't in this object
213
+					}
214
+
215
+					// if this isn't  a "list" type shortcode then we'll send along the data vanilla instead of in an array.
216
+					if (! in_array($sc_to_verify, $list_type_shortcodes)) {
217
+						$data_send = ! is_object($this->_data) && isset($this->_data['data']) ? $this->_data['data'] : $this->_data;
218
+					} else {
219
+						$data_send = $this->_data;
220
+					}
221
+
222
+					// is this a conditional type shortcode?  If it is then we actually parse the template here.
223
+					if ($this->_is_conditional_shortcode($shortcode)) {
224
+						// most shortcode parsers are not going to have a match for this shortcode and will return an
225
+						// empty string so we need to make sure that we're only replacing the template when there is a non empty string.
226
+						$parsed = $sc_obj->parser($shortcode, $data_send, $this->_data['extra_data']);
227
+						if ($parsed) {
228
+							$this->_template = $parsed;
229
+						}
230
+					}
231
+
232
+					$parsed = $sc_obj->parser($shortcode, $data_send, $this->_data['extra_data']);
233
+
234
+					$matched_code[] = $shortcode;
235
+					$sc_values[]    = $parsed;
236
+				}
237
+			}
238
+		}
239
+
240
+		// now we've got parsed values for all the shortcodes in the template so we can go ahead and swap the shortcodes out.
241
+		$parsed = str_replace(array_values($matched_code), array_values($sc_values), $this->_template);
242
+		return $parsed;
243
+	}
244
+
245
+
246
+	/**
247
+	 * Simply returns whether the given shortcode matches the structure for a conditional shortcode.
248
+	 *
249
+	 * Does it match this format: `[IF_`
250
+	 *
251
+	 * @param $shortcode
252
+	 */
253
+	protected function _is_conditional_shortcode($shortcode)
254
+	{
255
+		return strpos($shortcode, '[IF_') === 0;
256
+	}
257
+
258
+
259
+	/**
260
+	 * This sets the shortcodes property from the incoming array of valid shortcodes that corresponds to names of
261
+	 * various EE_Shortcode library objects
262
+	 *
263
+	 * @access private
264
+	 * @param array $valid_shortcodes an array of strings corresponding to EE_Shortcode Library objects
265
+	 * @return void
266
+	 */
267
+	private function _set_shortcodes($valid_shortcodes)
268
+	{
269
+		foreach ($valid_shortcodes as $shortcode_ref) {
270
+			$ref       = ucwords(str_replace('_', ' ', $shortcode_ref));
271
+			$ref       = str_replace(' ', '_', $ref);
272
+			$classname = 'EE_' . $ref . '_Shortcodes';
273
+			if (class_exists($classname)) {
274
+				$this->_shortcode_objs[] = new $classname();
275
+			}
276
+		}
277
+	}
278 278
 }
Please login to merge, or discard this patch.
core/domain/values/model/CustomSelects.php 2 patches
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -17,340 +17,340 @@
 block discarded – undo
17 17
  */
18 18
 class CustomSelects
19 19
 {
20
-    const TYPE_SIMPLE = 'simple';
21
-    const TYPE_COMPLEX = 'complex';
22
-    const TYPE_STRUCTURED = 'structured';
23
-
24
-    private $valid_operators = array('COUNT', 'SUM');
25
-
26
-
27
-    /**
28
-     * Original incoming select array
29
-     *
30
-     * @var array
31
-     */
32
-    private $original_selects;
33
-
34
-    /**
35
-     * Select string that can be added to the query
36
-     *
37
-     * @var string
38
-     */
39
-    private $columns_to_select_expression;
40
-
41
-
42
-    /**
43
-     * An array of aliases for the columns included in the incoming select array.
44
-     *
45
-     * @var array
46
-     */
47
-    private $column_aliases_in_select;
48
-
49
-
50
-    /**
51
-     * Enum representation of the "type" of array coming into this value object.
52
-     *
53
-     * @var string
54
-     */
55
-    private $type = '';
56
-
57
-
58
-    /**
59
-     * CustomSelects constructor.
60
-     * Incoming selects can be in one of the following formats:
61
-     * ---- self::TYPE_SIMPLE array ----
62
-     * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
63
-     * multiple columns to select as the values.
64
-     * eg. array( 'ATT_ID', 'REG_ID' )
65
-     * eg. array( '*' )
66
-     * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
67
-     * "structured" method.
68
-     * ---- self::TYPE_COMPLEX array ----
69
-     * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
70
-     * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
71
-     * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
72
-     * EEM_Base::$_valid_wpdb_data_types.
73
-     * eg. array( 'count' => array('count(REG_ID)', '%d') )
74
-     * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
75
-     * ---- self::TYPE_STRUCTURED array ---
76
-     * This is considered the "structured" type. This type is similar to the complex type except that the array attached
77
-     * to the column alias contains three values.  The first value is the qualified column name (which can include
78
-     * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
79
-     * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
80
-     * the second value.
81
-     * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
82
-     * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
83
-     * NOTE: mixing array types in the incoming $select will cause errors.
84
-     *
85
-     * @param array $selects
86
-     * @throws InvalidArgumentException
87
-     */
88
-    public function __construct(array $selects)
89
-    {
90
-        $this->original_selects = $selects;
91
-        $this->deriveType($selects);
92
-        $this->deriveParts($selects);
93
-    }
94
-
95
-
96
-    /**
97
-     * Derives what type of custom select has been sent in.
98
-     *
99
-     * @param array $selects
100
-     * @throws InvalidArgumentException
101
-     */
102
-    private function deriveType(array $selects)
103
-    {
104
-        // first if the first key for this array is an integer then its coming in as a simple format, so we'll also
105
-        // ensure all elements of the array are simple.
106
-        if (is_int(key($selects))) {
107
-            // let's ensure all keys are ints
108
-            $invalid_keys = array_filter(
109
-                array_keys($selects),
110
-                function ($value) {
111
-                    return ! is_int($value);
112
-                }
113
-            );
114
-            if (! empty($invalid_keys)) {
115
-                throw new InvalidArgumentException(
116
-                    sprintf(
117
-                        esc_html__(
118
-                            'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
119
-                            'event_espresso'
120
-                        ),
121
-                        self::TYPE_SIMPLE
122
-                    )
123
-                );
124
-            }
125
-            $this->type = self::TYPE_SIMPLE;
126
-            return;
127
-        }
128
-        // made it here so that means we've got either complex or structured selects.  Let's find out which by popping
129
-        // the first array element off.
130
-        $first_element = reset($selects);
131
-
132
-        if (! is_array($first_element)) {
133
-            throw new InvalidArgumentException(
134
-                sprintf(
135
-                    esc_html__(
136
-                        'Incoming array looks like its formatted as a "%1$s" or "%2$s" type.  However, the values in the array must be arrays themselves and they are not.',
137
-                        'event_espresso'
138
-                    ),
139
-                    self::TYPE_COMPLEX,
140
-                    self::TYPE_STRUCTURED
141
-                )
142
-            );
143
-        }
144
-        $this->type = count($first_element) === 2
145
-            ? self::TYPE_COMPLEX
146
-            : self::TYPE_STRUCTURED;
147
-    }
148
-
149
-
150
-    /**
151
-     * Sets up the various properties for the vo depending on type.
152
-     *
153
-     * @param array $selects
154
-     * @throws InvalidArgumentException
155
-     */
156
-    private function deriveParts(array $selects)
157
-    {
158
-        $column_parts = array();
159
-        switch ($this->type) {
160
-            case self::TYPE_SIMPLE:
161
-                $column_parts = $selects;
162
-                $this->column_aliases_in_select = $selects;
163
-                break;
164
-            case self::TYPE_COMPLEX:
165
-                foreach ($selects as $alias => $parts) {
166
-                    $this->validateSelectValueForType($parts, $alias);
167
-                    $column_parts[] = "{$parts[0]} AS {$alias}";
168
-                    $this->column_aliases_in_select[] = $alias;
169
-                }
170
-                break;
171
-            case self::TYPE_STRUCTURED:
172
-                foreach ($selects as $alias => $parts) {
173
-                    $this->validateSelectValueForType($parts, $alias);
174
-                    $column_parts[] = $parts[1] !== ''
175
-                        ? $this->assembleSelectStringWithOperator($parts, $alias)
176
-                        : "{$parts[0]} AS {$alias}";
177
-                    $this->column_aliases_in_select[] = $alias;
178
-                }
179
-                break;
180
-        }
181
-        $this->columns_to_select_expression = implode(', ', $column_parts);
182
-    }
183
-
184
-
185
-    /**
186
-     * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
187
-     *
188
-     * @param array  $select_parts
189
-     * @param string $alias
190
-     * @throws InvalidArgumentException
191
-     */
192
-    private function validateSelectValueForType(array $select_parts, $alias)
193
-    {
194
-        $valid_data_types = array('%d', '%s', '%f');
195
-        if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
196
-            throw new InvalidArgumentException(
197
-                sprintf(
198
-                    esc_html__(
199
-                        'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
200
-                        'event_espresso'
201
-                    ),
202
-                    $alias,
203
-                    $this->expectedSelectPartCountForType(),
204
-                    $this->type,
205
-                    count($select_parts)
206
-                )
207
-            );
208
-        }
209
-        // validate data type.
210
-        $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211
-        $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212
-
213
-        if (! in_array($data_type, $valid_data_types, true)) {
214
-            throw new InvalidArgumentException(
215
-                sprintf(
216
-                    esc_html__(
217
-                        'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
218
-                        'event_espresso'
219
-                    ),
220
-                    $data_type,
221
-                    $select_parts[0],
222
-                    $alias,
223
-                    implode(', ', $valid_data_types)
224
-                )
225
-            );
226
-        }
227
-    }
228
-
229
-
230
-    /**
231
-     * Each type will have an expected count of array elements, this returns what that expected count is.
232
-     *
233
-     * @param string $type
234
-     * @return int
235
-     */
236
-    private function expectedSelectPartCountForType($type = '')
237
-    {
238
-        $type = $type === '' ? $this->type : $type;
239
-        $types_count_map = array(
240
-            self::TYPE_COMPLEX    => 2,
241
-            self::TYPE_STRUCTURED => 3,
242
-        );
243
-        return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
244
-    }
245
-
246
-
247
-    /**
248
-     * Prepares the select statement part for for structured type selects.
249
-     *
250
-     * @param array  $select_parts
251
-     * @param string $alias
252
-     * @return string
253
-     * @throws InvalidArgumentException
254
-     */
255
-    private function assembleSelectStringWithOperator(array $select_parts, $alias)
256
-    {
257
-        $operator = strtoupper($select_parts[1]);
258
-        // validate operator
259
-        if (! in_array($operator, $this->valid_operators, true)) {
260
-            throw new InvalidArgumentException(
261
-                sprintf(
262
-                    esc_html__(
263
-                        'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
264
-                        'event_espresso'
265
-                    ),
266
-                    $operator,
267
-                    $alias,
268
-                    implode(', ', $this->valid_operators)
269
-                )
270
-            );
271
-        }
272
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
273
-    }
274
-
275
-
276
-    /**
277
-     * Return the datatype from the given select part.
278
-     * Remember the select_part has already been validated on object instantiation.
279
-     *
280
-     * @param array $select_part
281
-     * @return string
282
-     */
283
-    private function getDataTypeForSelectType(array $select_part)
284
-    {
285
-        switch ($this->type) {
286
-            case self::TYPE_COMPLEX:
287
-                return $select_part[1];
288
-            case self::TYPE_STRUCTURED:
289
-                return $select_part[2];
290
-            default:
291
-                return '';
292
-        }
293
-    }
294
-
295
-
296
-    /**
297
-     * Returns the original select array sent into the VO.
298
-     *
299
-     * @return array
300
-     */
301
-    public function originalSelects()
302
-    {
303
-        return $this->original_selects;
304
-    }
305
-
306
-
307
-    /**
308
-     * Returns the final assembled select expression derived from the incoming select array.
309
-     *
310
-     * @return string
311
-     */
312
-    public function columnsToSelectExpression()
313
-    {
314
-        return $this->columns_to_select_expression;
315
-    }
316
-
317
-
318
-    /**
319
-     * Returns all the column aliases derived from the incoming select array.
320
-     *
321
-     * @return array
322
-     */
323
-    public function columnAliases()
324
-    {
325
-        return $this->column_aliases_in_select;
326
-    }
327
-
328
-
329
-    /**
330
-     * Returns the enum type for the incoming select array.
331
-     *
332
-     * @return string
333
-     */
334
-    public function type()
335
-    {
336
-        return $this->type;
337
-    }
338
-
339
-
340
-    /**
341
-     * Return the datatype for the given column_alias
342
-     *
343
-     * @param string $column_alias
344
-     * @return string  (if there's no data type we return string as the default).
345
-     */
346
-    public function getDataTypeForAlias($column_alias)
347
-    {
348
-        if (
349
-            isset($this->original_selects[ $column_alias ])
350
-            && in_array($column_alias, $this->columnAliases(), true)
351
-        ) {
352
-            return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
353
-        }
354
-        return '%s';
355
-    }
20
+	const TYPE_SIMPLE = 'simple';
21
+	const TYPE_COMPLEX = 'complex';
22
+	const TYPE_STRUCTURED = 'structured';
23
+
24
+	private $valid_operators = array('COUNT', 'SUM');
25
+
26
+
27
+	/**
28
+	 * Original incoming select array
29
+	 *
30
+	 * @var array
31
+	 */
32
+	private $original_selects;
33
+
34
+	/**
35
+	 * Select string that can be added to the query
36
+	 *
37
+	 * @var string
38
+	 */
39
+	private $columns_to_select_expression;
40
+
41
+
42
+	/**
43
+	 * An array of aliases for the columns included in the incoming select array.
44
+	 *
45
+	 * @var array
46
+	 */
47
+	private $column_aliases_in_select;
48
+
49
+
50
+	/**
51
+	 * Enum representation of the "type" of array coming into this value object.
52
+	 *
53
+	 * @var string
54
+	 */
55
+	private $type = '';
56
+
57
+
58
+	/**
59
+	 * CustomSelects constructor.
60
+	 * Incoming selects can be in one of the following formats:
61
+	 * ---- self::TYPE_SIMPLE array ----
62
+	 * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
63
+	 * multiple columns to select as the values.
64
+	 * eg. array( 'ATT_ID', 'REG_ID' )
65
+	 * eg. array( '*' )
66
+	 * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
67
+	 * "structured" method.
68
+	 * ---- self::TYPE_COMPLEX array ----
69
+	 * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
70
+	 * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
71
+	 * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
72
+	 * EEM_Base::$_valid_wpdb_data_types.
73
+	 * eg. array( 'count' => array('count(REG_ID)', '%d') )
74
+	 * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
75
+	 * ---- self::TYPE_STRUCTURED array ---
76
+	 * This is considered the "structured" type. This type is similar to the complex type except that the array attached
77
+	 * to the column alias contains three values.  The first value is the qualified column name (which can include
78
+	 * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
79
+	 * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
80
+	 * the second value.
81
+	 * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
82
+	 * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
83
+	 * NOTE: mixing array types in the incoming $select will cause errors.
84
+	 *
85
+	 * @param array $selects
86
+	 * @throws InvalidArgumentException
87
+	 */
88
+	public function __construct(array $selects)
89
+	{
90
+		$this->original_selects = $selects;
91
+		$this->deriveType($selects);
92
+		$this->deriveParts($selects);
93
+	}
94
+
95
+
96
+	/**
97
+	 * Derives what type of custom select has been sent in.
98
+	 *
99
+	 * @param array $selects
100
+	 * @throws InvalidArgumentException
101
+	 */
102
+	private function deriveType(array $selects)
103
+	{
104
+		// first if the first key for this array is an integer then its coming in as a simple format, so we'll also
105
+		// ensure all elements of the array are simple.
106
+		if (is_int(key($selects))) {
107
+			// let's ensure all keys are ints
108
+			$invalid_keys = array_filter(
109
+				array_keys($selects),
110
+				function ($value) {
111
+					return ! is_int($value);
112
+				}
113
+			);
114
+			if (! empty($invalid_keys)) {
115
+				throw new InvalidArgumentException(
116
+					sprintf(
117
+						esc_html__(
118
+							'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
119
+							'event_espresso'
120
+						),
121
+						self::TYPE_SIMPLE
122
+					)
123
+				);
124
+			}
125
+			$this->type = self::TYPE_SIMPLE;
126
+			return;
127
+		}
128
+		// made it here so that means we've got either complex or structured selects.  Let's find out which by popping
129
+		// the first array element off.
130
+		$first_element = reset($selects);
131
+
132
+		if (! is_array($first_element)) {
133
+			throw new InvalidArgumentException(
134
+				sprintf(
135
+					esc_html__(
136
+						'Incoming array looks like its formatted as a "%1$s" or "%2$s" type.  However, the values in the array must be arrays themselves and they are not.',
137
+						'event_espresso'
138
+					),
139
+					self::TYPE_COMPLEX,
140
+					self::TYPE_STRUCTURED
141
+				)
142
+			);
143
+		}
144
+		$this->type = count($first_element) === 2
145
+			? self::TYPE_COMPLEX
146
+			: self::TYPE_STRUCTURED;
147
+	}
148
+
149
+
150
+	/**
151
+	 * Sets up the various properties for the vo depending on type.
152
+	 *
153
+	 * @param array $selects
154
+	 * @throws InvalidArgumentException
155
+	 */
156
+	private function deriveParts(array $selects)
157
+	{
158
+		$column_parts = array();
159
+		switch ($this->type) {
160
+			case self::TYPE_SIMPLE:
161
+				$column_parts = $selects;
162
+				$this->column_aliases_in_select = $selects;
163
+				break;
164
+			case self::TYPE_COMPLEX:
165
+				foreach ($selects as $alias => $parts) {
166
+					$this->validateSelectValueForType($parts, $alias);
167
+					$column_parts[] = "{$parts[0]} AS {$alias}";
168
+					$this->column_aliases_in_select[] = $alias;
169
+				}
170
+				break;
171
+			case self::TYPE_STRUCTURED:
172
+				foreach ($selects as $alias => $parts) {
173
+					$this->validateSelectValueForType($parts, $alias);
174
+					$column_parts[] = $parts[1] !== ''
175
+						? $this->assembleSelectStringWithOperator($parts, $alias)
176
+						: "{$parts[0]} AS {$alias}";
177
+					$this->column_aliases_in_select[] = $alias;
178
+				}
179
+				break;
180
+		}
181
+		$this->columns_to_select_expression = implode(', ', $column_parts);
182
+	}
183
+
184
+
185
+	/**
186
+	 * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
187
+	 *
188
+	 * @param array  $select_parts
189
+	 * @param string $alias
190
+	 * @throws InvalidArgumentException
191
+	 */
192
+	private function validateSelectValueForType(array $select_parts, $alias)
193
+	{
194
+		$valid_data_types = array('%d', '%s', '%f');
195
+		if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
196
+			throw new InvalidArgumentException(
197
+				sprintf(
198
+					esc_html__(
199
+						'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
200
+						'event_espresso'
201
+					),
202
+					$alias,
203
+					$this->expectedSelectPartCountForType(),
204
+					$this->type,
205
+					count($select_parts)
206
+				)
207
+			);
208
+		}
209
+		// validate data type.
210
+		$data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211
+		$data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212
+
213
+		if (! in_array($data_type, $valid_data_types, true)) {
214
+			throw new InvalidArgumentException(
215
+				sprintf(
216
+					esc_html__(
217
+						'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
218
+						'event_espresso'
219
+					),
220
+					$data_type,
221
+					$select_parts[0],
222
+					$alias,
223
+					implode(', ', $valid_data_types)
224
+				)
225
+			);
226
+		}
227
+	}
228
+
229
+
230
+	/**
231
+	 * Each type will have an expected count of array elements, this returns what that expected count is.
232
+	 *
233
+	 * @param string $type
234
+	 * @return int
235
+	 */
236
+	private function expectedSelectPartCountForType($type = '')
237
+	{
238
+		$type = $type === '' ? $this->type : $type;
239
+		$types_count_map = array(
240
+			self::TYPE_COMPLEX    => 2,
241
+			self::TYPE_STRUCTURED => 3,
242
+		);
243
+		return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
244
+	}
245
+
246
+
247
+	/**
248
+	 * Prepares the select statement part for for structured type selects.
249
+	 *
250
+	 * @param array  $select_parts
251
+	 * @param string $alias
252
+	 * @return string
253
+	 * @throws InvalidArgumentException
254
+	 */
255
+	private function assembleSelectStringWithOperator(array $select_parts, $alias)
256
+	{
257
+		$operator = strtoupper($select_parts[1]);
258
+		// validate operator
259
+		if (! in_array($operator, $this->valid_operators, true)) {
260
+			throw new InvalidArgumentException(
261
+				sprintf(
262
+					esc_html__(
263
+						'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
264
+						'event_espresso'
265
+					),
266
+					$operator,
267
+					$alias,
268
+					implode(', ', $this->valid_operators)
269
+				)
270
+			);
271
+		}
272
+		return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
273
+	}
274
+
275
+
276
+	/**
277
+	 * Return the datatype from the given select part.
278
+	 * Remember the select_part has already been validated on object instantiation.
279
+	 *
280
+	 * @param array $select_part
281
+	 * @return string
282
+	 */
283
+	private function getDataTypeForSelectType(array $select_part)
284
+	{
285
+		switch ($this->type) {
286
+			case self::TYPE_COMPLEX:
287
+				return $select_part[1];
288
+			case self::TYPE_STRUCTURED:
289
+				return $select_part[2];
290
+			default:
291
+				return '';
292
+		}
293
+	}
294
+
295
+
296
+	/**
297
+	 * Returns the original select array sent into the VO.
298
+	 *
299
+	 * @return array
300
+	 */
301
+	public function originalSelects()
302
+	{
303
+		return $this->original_selects;
304
+	}
305
+
306
+
307
+	/**
308
+	 * Returns the final assembled select expression derived from the incoming select array.
309
+	 *
310
+	 * @return string
311
+	 */
312
+	public function columnsToSelectExpression()
313
+	{
314
+		return $this->columns_to_select_expression;
315
+	}
316
+
317
+
318
+	/**
319
+	 * Returns all the column aliases derived from the incoming select array.
320
+	 *
321
+	 * @return array
322
+	 */
323
+	public function columnAliases()
324
+	{
325
+		return $this->column_aliases_in_select;
326
+	}
327
+
328
+
329
+	/**
330
+	 * Returns the enum type for the incoming select array.
331
+	 *
332
+	 * @return string
333
+	 */
334
+	public function type()
335
+	{
336
+		return $this->type;
337
+	}
338
+
339
+
340
+	/**
341
+	 * Return the datatype for the given column_alias
342
+	 *
343
+	 * @param string $column_alias
344
+	 * @return string  (if there's no data type we return string as the default).
345
+	 */
346
+	public function getDataTypeForAlias($column_alias)
347
+	{
348
+		if (
349
+			isset($this->original_selects[ $column_alias ])
350
+			&& in_array($column_alias, $this->columnAliases(), true)
351
+		) {
352
+			return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
353
+		}
354
+		return '%s';
355
+	}
356 356
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -107,11 +107,11 @@  discard block
 block discarded – undo
107 107
             // let's ensure all keys are ints
108 108
             $invalid_keys = array_filter(
109 109
                 array_keys($selects),
110
-                function ($value) {
110
+                function($value) {
111 111
                     return ! is_int($value);
112 112
                 }
113 113
             );
114
-            if (! empty($invalid_keys)) {
114
+            if ( ! empty($invalid_keys)) {
115 115
                 throw new InvalidArgumentException(
116 116
                     sprintf(
117 117
                         esc_html__(
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
         // the first array element off.
130 130
         $first_element = reset($selects);
131 131
 
132
-        if (! is_array($first_element)) {
132
+        if ( ! is_array($first_element)) {
133 133
             throw new InvalidArgumentException(
134 134
                 sprintf(
135 135
                     esc_html__(
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
         $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
211 211
         $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
212 212
 
213
-        if (! in_array($data_type, $valid_data_types, true)) {
213
+        if ( ! in_array($data_type, $valid_data_types, true)) {
214 214
             throw new InvalidArgumentException(
215 215
                 sprintf(
216 216
                     esc_html__(
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
             self::TYPE_COMPLEX    => 2,
241 241
             self::TYPE_STRUCTURED => 3,
242 242
         );
243
-        return isset($types_count_map[ $type ]) ? $types_count_map[ $type ] : 0;
243
+        return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
244 244
     }
245 245
 
246 246
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
     {
257 257
         $operator = strtoupper($select_parts[1]);
258 258
         // validate operator
259
-        if (! in_array($operator, $this->valid_operators, true)) {
259
+        if ( ! in_array($operator, $this->valid_operators, true)) {
260 260
             throw new InvalidArgumentException(
261 261
                 sprintf(
262 262
                     esc_html__(
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
                 )
270 270
             );
271 271
         }
272
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
272
+        return $operator.'('.$select_parts[0].') AS '.$alias;
273 273
     }
274 274
 
275 275
 
@@ -346,10 +346,10 @@  discard block
 block discarded – undo
346 346
     public function getDataTypeForAlias($column_alias)
347 347
     {
348 348
         if (
349
-            isset($this->original_selects[ $column_alias ])
349
+            isset($this->original_selects[$column_alias])
350 350
             && in_array($column_alias, $this->columnAliases(), true)
351 351
         ) {
352
-            return $this->getDataTypeForSelectType($this->original_selects[ $column_alias ]);
352
+            return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
353 353
         }
354 354
         return '%s';
355 355
     }
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Strategy.core.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
         if (is_array($this->_CPTs)) {
129 129
             foreach ($this->_CPTs as $CPT_type => $CPT) {
130 130
                 if (isset($CPT['plural_slug'])) {
131
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
+                    $_CPT_endpoints [(string) $CPT['plural_slug']] = $CPT_type;
132 132
                 }
133 133
             }
134 134
         }
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
     public function pre_get_posts($WP_Query)
152 152
     {
153 153
         // check that post-type is set
154
-        if (! $WP_Query instanceof WP_Query) {
154
+        if ( ! $WP_Query instanceof WP_Query) {
155 155
             return;
156 156
         }
157 157
         // add our conditionals
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
             $terms = EEM_Term::instance()->get_all_CPT_post_tags();
196 196
             foreach ($terms as $term) {
197 197
                 if ($term instanceof EE_Term) {
198
-                    $this->_CPT_terms[ $term->slug() ] = $term;
198
+                    $this->_CPT_terms[$term->slug()] = $term;
199 199
                 }
200 200
             }
201 201
         }
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
             // loop thru our taxonomies
261 261
             foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
262 262
                 // check if one of our taxonomies is set as a query var
263
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
+                if (isset($WP_Query->query[$CPT_taxonomy])) {
264 264
                     // but which CPT does that correspond to??? hmmm... guess we gotta go looping
265 265
                     foreach ($this->_CPTs as $post_type => $CPT) {
266 266
                         // verify our CPT has args, is public and has taxonomies set
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
                                     break;
285 285
                                 default:
286 286
                                     do_action(
287
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
287
+                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_'.$post_type.'_post_type',
288 288
                                         $WP_Query,
289 289
                                         $this
290 290
                                     );
@@ -309,11 +309,11 @@  discard block
 block discarded – undo
309 309
             // loop thru post_types as array
310 310
             foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
311 311
                 // is current query for an EE CPT ?
312
-                if (isset($this->_CPTs[ $post_type ])) {
312
+                if (isset($this->_CPTs[$post_type])) {
313 313
                     // is EE on or off ?
314 314
                     if (EE_Maintenance_Mode::instance()->level()) {
315 315
                         // reroute CPT template view to maintenance_mode.template.php
316
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
316
+                        if ( ! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
317 317
                             add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
318 318
                         }
319 319
                         if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
             'EventEspresso\core\CPTs\CptQueryModifier',
342 342
             array(
343 343
                 $post_type,
344
-                $this->_CPTs[ $post_type ],
344
+                $this->_CPTs[$post_type],
345 345
                 $WP_Query,
346 346
             )
347 347
         );
Please login to merge, or discard this patch.
Indentation   +445 added lines, -445 removed lines patch added patch discarded remove patch
@@ -15,449 +15,449 @@
 block discarded – undo
15 15
  */
16 16
 class EE_CPT_Strategy extends EE_Base
17 17
 {
18
-    /**
19
-     * @var EE_CPT_Strategy $_instance
20
-     */
21
-    private static $_instance;
22
-
23
-    /**
24
-     * the current page, if it utilizes CPTs
25
-     *
26
-     * @var array $CPT
27
-     */
28
-    protected $CPT;
29
-
30
-    /**
31
-     * return value from CustomPostTypeDefinitions::getDefinitions()
32
-     *
33
-     * @var array $_CPTs
34
-     */
35
-    protected $_CPTs = array();
36
-
37
-    /**
38
-     * @var array $_CPT_taxonomies
39
-     */
40
-    protected $_CPT_taxonomies = array();
41
-
42
-    /**
43
-     * @var array $_CPT_terms
44
-     */
45
-    protected $_CPT_terms = array();
46
-
47
-    /**
48
-     * @var array $_CPT_endpoints
49
-     */
50
-    protected $_CPT_endpoints = array();
51
-
52
-    /**
53
-     * @var EEM_Base $CPT_model
54
-     */
55
-    protected $CPT_model;
56
-
57
-    /**
58
-     * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
59
-     */
60
-    protected $query_modifier;
61
-
62
-
63
-    /**
64
-     * @singleton method used to instantiate class object
65
-     * @param CustomPostTypeDefinitions|null $custom_post_types
66
-     * @param CustomTaxonomyDefinitions|null $taxonomies
67
-     * @return EE_CPT_Strategy
68
-     */
69
-    public static function instance(
70
-        CustomPostTypeDefinitions $custom_post_types = null,
71
-        CustomTaxonomyDefinitions $taxonomies = null
72
-    ) {
73
-        // check if class object is instantiated
74
-        if (
75
-            ! self::$_instance instanceof EE_CPT_Strategy
76
-            && $custom_post_types instanceof CustomPostTypeDefinitions
77
-            && $taxonomies instanceof CustomTaxonomyDefinitions
78
-        ) {
79
-            self::$_instance = new self($custom_post_types, $taxonomies);
80
-        }
81
-        return self::$_instance;
82
-    }
83
-
84
-
85
-    /**
86
-     * @param CustomPostTypeDefinitions $custom_post_types
87
-     * @param CustomTaxonomyDefinitions $taxonomies
88
-     */
89
-    protected function __construct(
90
-        CustomPostTypeDefinitions $custom_post_types,
91
-        CustomTaxonomyDefinitions $taxonomies
92
-    ) {
93
-        // get CPT data
94
-        $this->_CPTs = $custom_post_types->getDefinitions();
95
-        $this->_CPT_endpoints = $this->_set_CPT_endpoints();
96
-        $this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
97
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
98
-    }
99
-
100
-
101
-    /**
102
-     * @return array
103
-     */
104
-    public function get_CPT_endpoints()
105
-    {
106
-        return $this->_CPT_endpoints;
107
-    }
108
-
109
-
110
-    /**
111
-     * @return array
112
-     */
113
-    public function get_CPT_taxonomies()
114
-    {
115
-        return $this->_CPT_taxonomies;
116
-    }
117
-
118
-
119
-    /**
120
-     * add CPT "slugs" to array of default espresso "pages"
121
-     *
122
-     * @return array
123
-     */
124
-    private function _set_CPT_endpoints()
125
-    {
126
-        $_CPT_endpoints = array();
127
-        if (is_array($this->_CPTs)) {
128
-            foreach ($this->_CPTs as $CPT_type => $CPT) {
129
-                if (isset($CPT['plural_slug'])) {
130
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
-                }
132
-            }
133
-        }
134
-        return $_CPT_endpoints;
135
-    }
136
-
137
-
138
-    /**
139
-     * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
140
-     * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
141
-     * adding EE objects to the post to facilitate further querying of related data etc)
142
-     *
143
-     * @param WP_Query $WP_Query
144
-     * @return void
145
-     * @throws \EE_Error
146
-     * @throws \InvalidArgumentException
147
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
148
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
149
-     */
150
-    public function pre_get_posts($WP_Query)
151
-    {
152
-        // check that post-type is set
153
-        if (! $WP_Query instanceof WP_Query) {
154
-            return;
155
-        }
156
-        // add our conditionals
157
-        $this->_set_EE_tags_on_WP_Query($WP_Query);
158
-        // check for terms
159
-        $this->_set_post_type_for_terms($WP_Query);
160
-        // make sure paging is always set
161
-        $this->_set_paging($WP_Query);
162
-        // is a taxonomy set ?
163
-        $this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
164
-        // loop thru post_types if set
165
-        $this->_process_WP_Query_post_types($WP_Query);
166
-    }
167
-
168
-
169
-    /**
170
-     * @param WP_Query $WP_Query
171
-     * @return void
172
-     */
173
-    private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
174
-    {
175
-        $WP_Query->is_espresso_event_single = false;
176
-        $WP_Query->is_espresso_event_archive = false;
177
-        $WP_Query->is_espresso_event_taxonomy = false;
178
-        $WP_Query->is_espresso_venue_single = false;
179
-        $WP_Query->is_espresso_venue_archive = false;
180
-        $WP_Query->is_espresso_venue_taxonomy = false;
181
-    }
182
-
183
-
184
-    /**
185
-     * @return void
186
-     * @throws EE_Error
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidInterfaceException
190
-     */
191
-    private function _set_CPT_terms()
192
-    {
193
-        if (empty($this->_CPT_terms)) {
194
-            $terms = EEM_Term::instance()->get_all_CPT_post_tags();
195
-            foreach ($terms as $term) {
196
-                if ($term instanceof EE_Term) {
197
-                    $this->_CPT_terms[ $term->slug() ] = $term;
198
-                }
199
-            }
200
-        }
201
-    }
202
-
203
-
204
-    /**
205
-     * @param WP_Query $WP_Query
206
-     * @return void
207
-     * @throws EE_Error
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     */
212
-    private function _set_post_type_for_terms(WP_Query $WP_Query)
213
-    {
214
-        // is a tag set ?
215
-        if (isset($WP_Query->query['tag'])) {
216
-            // get term for tag
217
-            $term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
218
-            // verify the term
219
-            if ($term instanceof EE_Term) {
220
-                $term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
221
-                $term->post_type = apply_filters(
222
-                    'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
223
-                    $term->post_type,
224
-                    $term
225
-                );
226
-                // if a post type is already set
227
-                if (isset($WP_Query->query_vars['post_type'])) {
228
-                    // add to existing array
229
-                    $term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
230
-                }
231
-                // just set post_type to our CPT
232
-                $WP_Query->set('post_type', array_unique($term->post_type));
233
-            }
234
-        }
235
-    }
236
-
237
-
238
-    /**
239
-     * @param WP_Query $WP_Query
240
-     * @return void
241
-     */
242
-    public function _set_paging($WP_Query)
243
-    {
244
-        if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
245
-            $page = get_query_var('page') ? get_query_var('page') : null;
246
-            $paged = get_query_var('paged') ? get_query_var('paged') : $page;
247
-            $WP_Query->set('paged', $paged);
248
-        }
249
-    }
250
-
251
-
252
-    /**
253
-     * @param \WP_Query $WP_Query
254
-     */
255
-    protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
256
-    {
257
-        // is a taxonomy set ?
258
-        if ($WP_Query->is_tax) {
259
-            // loop thru our taxonomies
260
-            foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
261
-                // check if one of our taxonomies is set as a query var
262
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
-                    // but which CPT does that correspond to??? hmmm... guess we gotta go looping
264
-                    foreach ($this->_CPTs as $post_type => $CPT) {
265
-                        // verify our CPT has args, is public and has taxonomies set
266
-                        if (
267
-                            isset($CPT['args']['public'])
268
-                            && $CPT['args']['public']
269
-                            && ! empty($CPT['args']['taxonomies'])
270
-                            && in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
271
-                        ) {
272
-                            // if so, then add this CPT post_type to the current query's array of post_types'
273
-                            $WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
274
-                                ? (array) $WP_Query->query_vars['post_type']
275
-                                : array();
276
-                            $WP_Query->query_vars['post_type'][] = $post_type;
277
-                            switch ($post_type) {
278
-                                case 'espresso_events':
279
-                                    $WP_Query->is_espresso_event_taxonomy = true;
280
-                                    break;
281
-                                case 'espresso_venues':
282
-                                    $WP_Query->is_espresso_venue_taxonomy = true;
283
-                                    break;
284
-                                default:
285
-                                    do_action(
286
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
287
-                                        $WP_Query,
288
-                                        $this
289
-                                    );
290
-                            }
291
-                        }
292
-                    }
293
-                }
294
-            }
295
-        }
296
-    }
297
-
298
-
299
-    /**
300
-     * @param \WP_Query $WP_Query
301
-     * @throws InvalidArgumentException
302
-     * @throws InvalidDataTypeException
303
-     * @throws InvalidInterfaceException
304
-     */
305
-    protected function _process_WP_Query_post_types(WP_Query $WP_Query)
306
-    {
307
-        if (isset($WP_Query->query_vars['post_type'])) {
308
-            // loop thru post_types as array
309
-            foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
310
-                // is current query for an EE CPT ?
311
-                if (isset($this->_CPTs[ $post_type ])) {
312
-                    // is EE on or off ?
313
-                    if (EE_Maintenance_Mode::instance()->level()) {
314
-                        // reroute CPT template view to maintenance_mode.template.php
315
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
316
-                            add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
317
-                        }
318
-                        if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
319
-                            add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
320
-                        }
321
-                        return;
322
-                    }
323
-                    $this->_generate_CptQueryModifier($WP_Query, $post_type);
324
-                }
325
-            }
326
-        }
327
-    }
328
-
329
-
330
-    /**
331
-     * @param \WP_Query $WP_Query
332
-     * @param string    $post_type
333
-     * @throws InvalidArgumentException
334
-     * @throws InvalidDataTypeException
335
-     * @throws InvalidInterfaceException
336
-     */
337
-    protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
338
-    {
339
-        $this->query_modifier = LoaderFactory::getLoader()->getShared(
340
-            'EventEspresso\core\CPTs\CptQueryModifier',
341
-            array(
342
-                $post_type,
343
-                $this->_CPTs[ $post_type ],
344
-                $WP_Query,
345
-            )
346
-        );
347
-        $this->_CPT_taxonomies = $this->query_modifier->taxonomies();
348
-    }
349
-
350
-
351
-    /**
352
-     * inject_EE_shortcode_placeholder
353
-     * in order to display the M-Mode notice on our CPT routes,
354
-     * we need to first inject what looks like one of our shortcodes,
355
-     * so that it can be replaced with the actual M-Mode notice
356
-     *
357
-     * @return string
358
-     */
359
-    public function inject_EE_shortcode_placeholder()
360
-    {
361
-        return '[ESPRESSO_';
362
-    }
363
-
364
-
365
-    /**
366
-     * @deprecated
367
-     * @since  4.8.41
368
-     * @return void
369
-     */
370
-    public function _possibly_set_ee_request_var()
371
-    {
372
-        $this->query_modifier->setRequestVarsIfCpt();
373
-    }
374
-
375
-
376
-    /**
377
-     * @deprecated
378
-     * @since  4.8.41
379
-     * @param  $SQL
380
-     * @return string
381
-     */
382
-    public function posts_fields($SQL)
383
-    {
384
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
385
-            return $this->query_modifier->postsFields($SQL);
386
-        }
387
-        return $SQL;
388
-    }
389
-
390
-
391
-    /**
392
-     * @deprecated
393
-     * @since  4.8.41
394
-     * @param  $SQL
395
-     * @return string
396
-     */
397
-    public function posts_join($SQL)
398
-    {
399
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
400
-            return $this->query_modifier->postsJoin($SQL);
401
-        }
402
-        return $SQL;
403
-    }
404
-
405
-
406
-    /**
407
-     * @deprecated
408
-     * @since  4.8.41
409
-     * @param  \WP_Post[] $posts
410
-     * @return \WP_Post[]
411
-     */
412
-    public function the_posts($posts)
413
-    {
414
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
415
-            $this->query_modifier->thePosts($posts);
416
-        }
417
-        return $posts;
418
-    }
419
-
420
-
421
-    /**
422
-     * @deprecated
423
-     * @since  4.8.41
424
-     * @param $url
425
-     * @param $ID
426
-     * @return string
427
-     */
428
-    public function get_edit_post_link($url, $ID)
429
-    {
430
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
431
-            return $this->query_modifier->getEditPostLink($url, $ID);
432
-        }
433
-        return '';
434
-    }
435
-
436
-
437
-    /**
438
-     * @deprecated
439
-     * @since  4.8.41
440
-     * @param null $WP_Query
441
-     */
442
-    protected function _do_template_filters($WP_Query = null)
443
-    {
444
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
445
-            $this->query_modifier->addTemplateFilters();
446
-        }
447
-    }
448
-
449
-
450
-    /**
451
-     * @deprecated
452
-     * @since  4.8.41
453
-     * @param string $current_template Existing default template path derived for this page call.
454
-     * @return string the path to the full template file.
455
-     */
456
-    public function single_cpt_template($current_template)
457
-    {
458
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
459
-            return $this->query_modifier->singleCptTemplate($current_template);
460
-        }
461
-        return $current_template;
462
-    }
18
+	/**
19
+	 * @var EE_CPT_Strategy $_instance
20
+	 */
21
+	private static $_instance;
22
+
23
+	/**
24
+	 * the current page, if it utilizes CPTs
25
+	 *
26
+	 * @var array $CPT
27
+	 */
28
+	protected $CPT;
29
+
30
+	/**
31
+	 * return value from CustomPostTypeDefinitions::getDefinitions()
32
+	 *
33
+	 * @var array $_CPTs
34
+	 */
35
+	protected $_CPTs = array();
36
+
37
+	/**
38
+	 * @var array $_CPT_taxonomies
39
+	 */
40
+	protected $_CPT_taxonomies = array();
41
+
42
+	/**
43
+	 * @var array $_CPT_terms
44
+	 */
45
+	protected $_CPT_terms = array();
46
+
47
+	/**
48
+	 * @var array $_CPT_endpoints
49
+	 */
50
+	protected $_CPT_endpoints = array();
51
+
52
+	/**
53
+	 * @var EEM_Base $CPT_model
54
+	 */
55
+	protected $CPT_model;
56
+
57
+	/**
58
+	 * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
59
+	 */
60
+	protected $query_modifier;
61
+
62
+
63
+	/**
64
+	 * @singleton method used to instantiate class object
65
+	 * @param CustomPostTypeDefinitions|null $custom_post_types
66
+	 * @param CustomTaxonomyDefinitions|null $taxonomies
67
+	 * @return EE_CPT_Strategy
68
+	 */
69
+	public static function instance(
70
+		CustomPostTypeDefinitions $custom_post_types = null,
71
+		CustomTaxonomyDefinitions $taxonomies = null
72
+	) {
73
+		// check if class object is instantiated
74
+		if (
75
+			! self::$_instance instanceof EE_CPT_Strategy
76
+			&& $custom_post_types instanceof CustomPostTypeDefinitions
77
+			&& $taxonomies instanceof CustomTaxonomyDefinitions
78
+		) {
79
+			self::$_instance = new self($custom_post_types, $taxonomies);
80
+		}
81
+		return self::$_instance;
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param CustomPostTypeDefinitions $custom_post_types
87
+	 * @param CustomTaxonomyDefinitions $taxonomies
88
+	 */
89
+	protected function __construct(
90
+		CustomPostTypeDefinitions $custom_post_types,
91
+		CustomTaxonomyDefinitions $taxonomies
92
+	) {
93
+		// get CPT data
94
+		$this->_CPTs = $custom_post_types->getDefinitions();
95
+		$this->_CPT_endpoints = $this->_set_CPT_endpoints();
96
+		$this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
97
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
98
+	}
99
+
100
+
101
+	/**
102
+	 * @return array
103
+	 */
104
+	public function get_CPT_endpoints()
105
+	{
106
+		return $this->_CPT_endpoints;
107
+	}
108
+
109
+
110
+	/**
111
+	 * @return array
112
+	 */
113
+	public function get_CPT_taxonomies()
114
+	{
115
+		return $this->_CPT_taxonomies;
116
+	}
117
+
118
+
119
+	/**
120
+	 * add CPT "slugs" to array of default espresso "pages"
121
+	 *
122
+	 * @return array
123
+	 */
124
+	private function _set_CPT_endpoints()
125
+	{
126
+		$_CPT_endpoints = array();
127
+		if (is_array($this->_CPTs)) {
128
+			foreach ($this->_CPTs as $CPT_type => $CPT) {
129
+				if (isset($CPT['plural_slug'])) {
130
+					$_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
+				}
132
+			}
133
+		}
134
+		return $_CPT_endpoints;
135
+	}
136
+
137
+
138
+	/**
139
+	 * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
140
+	 * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
141
+	 * adding EE objects to the post to facilitate further querying of related data etc)
142
+	 *
143
+	 * @param WP_Query $WP_Query
144
+	 * @return void
145
+	 * @throws \EE_Error
146
+	 * @throws \InvalidArgumentException
147
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
148
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
149
+	 */
150
+	public function pre_get_posts($WP_Query)
151
+	{
152
+		// check that post-type is set
153
+		if (! $WP_Query instanceof WP_Query) {
154
+			return;
155
+		}
156
+		// add our conditionals
157
+		$this->_set_EE_tags_on_WP_Query($WP_Query);
158
+		// check for terms
159
+		$this->_set_post_type_for_terms($WP_Query);
160
+		// make sure paging is always set
161
+		$this->_set_paging($WP_Query);
162
+		// is a taxonomy set ?
163
+		$this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
164
+		// loop thru post_types if set
165
+		$this->_process_WP_Query_post_types($WP_Query);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param WP_Query $WP_Query
171
+	 * @return void
172
+	 */
173
+	private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
174
+	{
175
+		$WP_Query->is_espresso_event_single = false;
176
+		$WP_Query->is_espresso_event_archive = false;
177
+		$WP_Query->is_espresso_event_taxonomy = false;
178
+		$WP_Query->is_espresso_venue_single = false;
179
+		$WP_Query->is_espresso_venue_archive = false;
180
+		$WP_Query->is_espresso_venue_taxonomy = false;
181
+	}
182
+
183
+
184
+	/**
185
+	 * @return void
186
+	 * @throws EE_Error
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidInterfaceException
190
+	 */
191
+	private function _set_CPT_terms()
192
+	{
193
+		if (empty($this->_CPT_terms)) {
194
+			$terms = EEM_Term::instance()->get_all_CPT_post_tags();
195
+			foreach ($terms as $term) {
196
+				if ($term instanceof EE_Term) {
197
+					$this->_CPT_terms[ $term->slug() ] = $term;
198
+				}
199
+			}
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * @param WP_Query $WP_Query
206
+	 * @return void
207
+	 * @throws EE_Error
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 */
212
+	private function _set_post_type_for_terms(WP_Query $WP_Query)
213
+	{
214
+		// is a tag set ?
215
+		if (isset($WP_Query->query['tag'])) {
216
+			// get term for tag
217
+			$term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
218
+			// verify the term
219
+			if ($term instanceof EE_Term) {
220
+				$term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
221
+				$term->post_type = apply_filters(
222
+					'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
223
+					$term->post_type,
224
+					$term
225
+				);
226
+				// if a post type is already set
227
+				if (isset($WP_Query->query_vars['post_type'])) {
228
+					// add to existing array
229
+					$term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
230
+				}
231
+				// just set post_type to our CPT
232
+				$WP_Query->set('post_type', array_unique($term->post_type));
233
+			}
234
+		}
235
+	}
236
+
237
+
238
+	/**
239
+	 * @param WP_Query $WP_Query
240
+	 * @return void
241
+	 */
242
+	public function _set_paging($WP_Query)
243
+	{
244
+		if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
245
+			$page = get_query_var('page') ? get_query_var('page') : null;
246
+			$paged = get_query_var('paged') ? get_query_var('paged') : $page;
247
+			$WP_Query->set('paged', $paged);
248
+		}
249
+	}
250
+
251
+
252
+	/**
253
+	 * @param \WP_Query $WP_Query
254
+	 */
255
+	protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
256
+	{
257
+		// is a taxonomy set ?
258
+		if ($WP_Query->is_tax) {
259
+			// loop thru our taxonomies
260
+			foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
261
+				// check if one of our taxonomies is set as a query var
262
+				if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
+					// but which CPT does that correspond to??? hmmm... guess we gotta go looping
264
+					foreach ($this->_CPTs as $post_type => $CPT) {
265
+						// verify our CPT has args, is public and has taxonomies set
266
+						if (
267
+							isset($CPT['args']['public'])
268
+							&& $CPT['args']['public']
269
+							&& ! empty($CPT['args']['taxonomies'])
270
+							&& in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
271
+						) {
272
+							// if so, then add this CPT post_type to the current query's array of post_types'
273
+							$WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
274
+								? (array) $WP_Query->query_vars['post_type']
275
+								: array();
276
+							$WP_Query->query_vars['post_type'][] = $post_type;
277
+							switch ($post_type) {
278
+								case 'espresso_events':
279
+									$WP_Query->is_espresso_event_taxonomy = true;
280
+									break;
281
+								case 'espresso_venues':
282
+									$WP_Query->is_espresso_venue_taxonomy = true;
283
+									break;
284
+								default:
285
+									do_action(
286
+										'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
287
+										$WP_Query,
288
+										$this
289
+									);
290
+							}
291
+						}
292
+					}
293
+				}
294
+			}
295
+		}
296
+	}
297
+
298
+
299
+	/**
300
+	 * @param \WP_Query $WP_Query
301
+	 * @throws InvalidArgumentException
302
+	 * @throws InvalidDataTypeException
303
+	 * @throws InvalidInterfaceException
304
+	 */
305
+	protected function _process_WP_Query_post_types(WP_Query $WP_Query)
306
+	{
307
+		if (isset($WP_Query->query_vars['post_type'])) {
308
+			// loop thru post_types as array
309
+			foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
310
+				// is current query for an EE CPT ?
311
+				if (isset($this->_CPTs[ $post_type ])) {
312
+					// is EE on or off ?
313
+					if (EE_Maintenance_Mode::instance()->level()) {
314
+						// reroute CPT template view to maintenance_mode.template.php
315
+						if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
316
+							add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
317
+						}
318
+						if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
319
+							add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
320
+						}
321
+						return;
322
+					}
323
+					$this->_generate_CptQueryModifier($WP_Query, $post_type);
324
+				}
325
+			}
326
+		}
327
+	}
328
+
329
+
330
+	/**
331
+	 * @param \WP_Query $WP_Query
332
+	 * @param string    $post_type
333
+	 * @throws InvalidArgumentException
334
+	 * @throws InvalidDataTypeException
335
+	 * @throws InvalidInterfaceException
336
+	 */
337
+	protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
338
+	{
339
+		$this->query_modifier = LoaderFactory::getLoader()->getShared(
340
+			'EventEspresso\core\CPTs\CptQueryModifier',
341
+			array(
342
+				$post_type,
343
+				$this->_CPTs[ $post_type ],
344
+				$WP_Query,
345
+			)
346
+		);
347
+		$this->_CPT_taxonomies = $this->query_modifier->taxonomies();
348
+	}
349
+
350
+
351
+	/**
352
+	 * inject_EE_shortcode_placeholder
353
+	 * in order to display the M-Mode notice on our CPT routes,
354
+	 * we need to first inject what looks like one of our shortcodes,
355
+	 * so that it can be replaced with the actual M-Mode notice
356
+	 *
357
+	 * @return string
358
+	 */
359
+	public function inject_EE_shortcode_placeholder()
360
+	{
361
+		return '[ESPRESSO_';
362
+	}
363
+
364
+
365
+	/**
366
+	 * @deprecated
367
+	 * @since  4.8.41
368
+	 * @return void
369
+	 */
370
+	public function _possibly_set_ee_request_var()
371
+	{
372
+		$this->query_modifier->setRequestVarsIfCpt();
373
+	}
374
+
375
+
376
+	/**
377
+	 * @deprecated
378
+	 * @since  4.8.41
379
+	 * @param  $SQL
380
+	 * @return string
381
+	 */
382
+	public function posts_fields($SQL)
383
+	{
384
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
385
+			return $this->query_modifier->postsFields($SQL);
386
+		}
387
+		return $SQL;
388
+	}
389
+
390
+
391
+	/**
392
+	 * @deprecated
393
+	 * @since  4.8.41
394
+	 * @param  $SQL
395
+	 * @return string
396
+	 */
397
+	public function posts_join($SQL)
398
+	{
399
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
400
+			return $this->query_modifier->postsJoin($SQL);
401
+		}
402
+		return $SQL;
403
+	}
404
+
405
+
406
+	/**
407
+	 * @deprecated
408
+	 * @since  4.8.41
409
+	 * @param  \WP_Post[] $posts
410
+	 * @return \WP_Post[]
411
+	 */
412
+	public function the_posts($posts)
413
+	{
414
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
415
+			$this->query_modifier->thePosts($posts);
416
+		}
417
+		return $posts;
418
+	}
419
+
420
+
421
+	/**
422
+	 * @deprecated
423
+	 * @since  4.8.41
424
+	 * @param $url
425
+	 * @param $ID
426
+	 * @return string
427
+	 */
428
+	public function get_edit_post_link($url, $ID)
429
+	{
430
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
431
+			return $this->query_modifier->getEditPostLink($url, $ID);
432
+		}
433
+		return '';
434
+	}
435
+
436
+
437
+	/**
438
+	 * @deprecated
439
+	 * @since  4.8.41
440
+	 * @param null $WP_Query
441
+	 */
442
+	protected function _do_template_filters($WP_Query = null)
443
+	{
444
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
445
+			$this->query_modifier->addTemplateFilters();
446
+		}
447
+	}
448
+
449
+
450
+	/**
451
+	 * @deprecated
452
+	 * @since  4.8.41
453
+	 * @param string $current_template Existing default template path derived for this page call.
454
+	 * @return string the path to the full template file.
455
+	 */
456
+	public function single_cpt_template($current_template)
457
+	{
458
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
459
+			return $this->query_modifier->singleCptTemplate($current_template);
460
+		}
461
+		return $current_template;
462
+	}
463 463
 }
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Event_Strategy.core.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -122,13 +122,13 @@  discard block
 block discarded – undo
122 122
             )
123 123
         ) {
124 124
             // adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
125
-            $SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
125
+            $SQL .= ', '.EEM_Datetime::instance()->table().'.* ';
126 126
             if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
127 127
                 // because we only want to retrieve the next upcoming datetime for each event:
128 128
                 // add something like:
129 129
                 // ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
130 130
                 // to WP Query SELECT statement
131
-                $SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
131
+                $SQL .= ', MIN( '.EEM_Datetime::instance()->table().'.DTT_EVT_start ) as event_start_date ';
132 132
             }
133 133
         }
134 134
         return $SQL;
@@ -158,9 +158,9 @@  discard block
 block discarded – undo
158 158
             // adds something like:
159 159
             // " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
160 160
             // to WP Query JOIN statement
161
-            $SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
162
-                    . '.ID = ' . EEM_Datetime::instance()->table() . '.'
163
-                    . EEM_Event::instance()->primary_key_name() . ' ) ';
161
+            $SQL .= ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.EEM_Event::instance()->table()
162
+                    . '.ID = '.EEM_Datetime::instance()->table().'.'
163
+                    . EEM_Event::instance()->primary_key_name().' ) ';
164 164
         }
165 165
         return $SQL;
166 166
     }
@@ -190,8 +190,8 @@  discard block
 block discarded – undo
190 190
                 || ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
191 191
                 || ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
192 192
             ) {
193
-                $SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
194
-                        . current_time('mysql', true) . "' ";
193
+                $SQL .= ' AND '.EEM_Datetime::instance()->table().".DTT_EVT_end > '"
194
+                        . current_time('mysql', true)."' ";
195 195
             }
196 196
         }
197 197
         return $SQL;
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
             // but we want to only show each event only once
240 240
             // (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
241 241
             global $wpdb;
242
-            $SQL = $wpdb->posts . '.ID ';
242
+            $SQL = $wpdb->posts.'.ID ';
243 243
         }
244 244
         return $SQL;
245 245
     }
Please login to merge, or discard this patch.
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -9,244 +9,244 @@
 block discarded – undo
9 9
  */
10 10
 class EE_CPT_Event_Strategy
11 11
 {
12
-    /**
13
-     * the current page, if it utilizes CPTs
14
-     *
15
-     * @var object $CPT
16
-     */
17
-    protected $CPT;
18
-
19
-
20
-    /**
21
-     * @param array|WP_Query|null $wp_query
22
-     * @param array         $CPT
23
-     */
24
-    public function __construct($wp_query, array $CPT = [])
25
-    {
26
-        if ($wp_query instanceof WP_Query) {
27
-            $WP_Query  = $wp_query;
28
-            $this->CPT = $CPT;
29
-        } else {
30
-            $WP_Query  = $wp_query['WP_Query'] ?? null;
31
-            $this->CPT = $wp_query['CPT'] ?? null;
32
-        }
33
-        // !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
34
-        // here's the list of available filters in the WP_Query object
35
-        // 'posts_where'
36
-        // 'posts_where_paged'
37
-        // 'posts_groupby'
38
-        // 'posts_join_paged'
39
-        // 'posts_orderby'
40
-        // 'posts_distinct'
41
-        // 'post_limits'
42
-        // 'posts_fields'
43
-        // 'posts_join'
44
-        $this->_add_filters();
45
-        if ($WP_Query instanceof WP_Query) {
46
-            $WP_Query->is_espresso_event_single   = is_singular()
47
-                                                    && isset($WP_Query->query->post_type)
48
-                                                    && $WP_Query->query->post_type === 'espresso_events';
49
-            $WP_Query->is_espresso_event_archive  = is_post_type_archive('espresso_events');
50
-            $WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
51
-        }
52
-    }
53
-
54
-
55
-    /**
56
-     * When an instance of this class is created, we add our filters
57
-     * (which will get removed in case the next call to get_posts ISN'T
58
-     * for event CPTs)
59
-     */
60
-    protected function _add_filters()
61
-    {
62
-        add_filter('posts_fields', [$this, 'posts_fields'], 1, 2);
63
-        add_filter('posts_join', [$this, 'posts_join'], 1, 2);
64
-        add_filter('posts_where', [$this, 'posts_where'], 10, 2);
65
-        // add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
66
-        add_filter('posts_orderby', [$this, 'posts_orderby'], 1, 2);
67
-        add_filter('posts_groupby', [$this, 'posts_groupby'], 1, 2);
68
-        add_action('posts_selection', [$this, 'remove_filters']);
69
-    }
70
-
71
-
72
-    /**
73
-     * public access to _remove_filters()
74
-     *
75
-     * @since 4.9.63.p
76
-     */
77
-    public function remove_filters()
78
-    {
79
-        $this->_remove_filters();
80
-    }
81
-
82
-
83
-    /**
84
-     * Should eb called when the last filter or hook is fired for this CPT strategy.
85
-     * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
86
-     * we don't want to join to the datetime table when querying for venues, do we!?)
87
-     */
88
-    protected function _remove_filters()
89
-    {
90
-        remove_filter('posts_fields', [$this, 'posts_fields'], 1);
91
-        remove_filter('posts_join', [$this, 'posts_join'], 1);
92
-        remove_filter('posts_where', [$this, 'posts_where']);
93
-        // remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
94
-        remove_filter('posts_orderby', [$this, 'posts_orderby'], 1);
95
-        remove_filter('posts_groupby', [$this, 'posts_groupby'], 1);
96
-        remove_action('posts_selection', [$this, 'remove_filters']);
97
-    }
98
-
99
-
100
-    /**
101
-     * @param string        $SQL
102
-     * @param WP_Query|null $wp_query
103
-     * @return    string
104
-     * @throws EE_Error
105
-     */
106
-    public function posts_fields(string $SQL, ?WP_Query $wp_query): string
107
-    {
108
-        if (
109
-            $wp_query instanceof WP_Query
110
-            && (
111
-                $wp_query->is_espresso_event_single
112
-                || $wp_query->is_espresso_event_archive
113
-                || $wp_query->is_espresso_event_taxonomy
114
-            )
115
-        ) {
116
-            // adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
117
-            $SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
118
-            if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
119
-                // because we only want to retrieve the next upcoming datetime for each event:
120
-                // add something like:
121
-                // ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
122
-                // to WP Query SELECT statement
123
-                $SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
124
-            }
125
-        }
126
-        return $SQL;
127
-    }
128
-
129
-
130
-    /**
131
-     * @param string        $SQL
132
-     * @param WP_Query|null $wp_query
133
-     * @return string
134
-     * @throws EE_Error
135
-     */
136
-    public function posts_join(string $SQL, ?WP_Query $wp_query): string
137
-    {
138
-        if (
139
-            $wp_query instanceof WP_Query
140
-            && (
141
-                $wp_query->is_espresso_event_single
142
-                || $wp_query->is_espresso_event_archive
143
-                || $wp_query->is_espresso_event_taxonomy
144
-            )
145
-        ) {
146
-            // adds something like:
147
-            // " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
148
-            // to WP Query JOIN statement
149
-            $SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
150
-                    . '.ID = ' . EEM_Datetime::instance()->table() . '.'
151
-                    . EEM_Event::instance()->primary_key_name() . ' ) ';
152
-        }
153
-        return $SQL;
154
-    }
155
-
156
-
157
-    /**
158
-     * @param string        $SQL
159
-     * @param WP_Query|null $wp_query
160
-     * @return string
161
-     * @throws EE_Error
162
-     */
163
-    public function posts_where(string $SQL, ?WP_Query $wp_query): string
164
-    {
165
-        if (
166
-            $wp_query instanceof WP_Query
167
-            && (
168
-                $wp_query->is_espresso_event_archive
169
-                || $wp_query->is_espresso_event_taxonomy
170
-            )
171
-        ) {
172
-            if (
173
-                ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
174
-                || ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
175
-                || ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
176
-            ) {
177
-                $SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
178
-                        . current_time('mysql', true) . "' ";
179
-            }
180
-        }
181
-        return $SQL;
182
-    }
183
-
184
-
185
-    /**
186
-     * @param string        $SQL
187
-     * @param WP_Query|null $wp_query
188
-     * @return string
189
-     */
190
-    public function posts_orderby(string $SQL, ?WP_Query $wp_query): string
191
-    {
192
-        if (
193
-            $wp_query instanceof WP_Query
194
-            && (
195
-                $wp_query->is_espresso_event_archive
196
-                || $wp_query->is_espresso_event_taxonomy
197
-            )
198
-        ) {
199
-            $SQL = ' event_start_date ASC ';
200
-        }
201
-        return $SQL;
202
-    }
203
-
204
-
205
-    /**
206
-     * @param string        $SQL
207
-     * @param WP_Query|null $wp_query
208
-     * @return string
209
-     */
210
-    public function posts_groupby(string $SQL, ?WP_Query $wp_query): string
211
-    {
212
-        if (
213
-            $wp_query instanceof WP_Query
214
-            && (
215
-                $wp_query->is_espresso_event_archive
216
-                || $wp_query->is_espresso_event_taxonomy
217
-            )
218
-        ) {
219
-            // TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
220
-            // we're joining to the datetimes table, where there can be MANY datetimes for a single event,
221
-            // but we want to only show each event only once
222
-            // (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
223
-            global $wpdb;
224
-            $SQL = $wpdb->posts . '.ID ';
225
-        }
226
-        return $SQL;
227
-    }
228
-
229
-
230
-    /**
231
-     * @param array         $posts
232
-     * @param WP_Query|null $wp_query
233
-     * @return array
234
-     */
235
-    public function the_posts(array $posts, ?WP_Query $wp_query): array
236
-    {
237
-        return $posts;
238
-    }
239
-
240
-
241
-    /**
242
-     * @param mixed           $meta_value
243
-     * @param int|string      $post_id
244
-     * @param int|string      $meta_key
245
-     * @param bool|int|string $single
246
-     * @return mixed
247
-     */
248
-    public function get_EE_post_type_metadata($meta_value, $post_id, $meta_key, $single)
249
-    {
250
-        return $meta_value;
251
-    }
12
+	/**
13
+	 * the current page, if it utilizes CPTs
14
+	 *
15
+	 * @var object $CPT
16
+	 */
17
+	protected $CPT;
18
+
19
+
20
+	/**
21
+	 * @param array|WP_Query|null $wp_query
22
+	 * @param array         $CPT
23
+	 */
24
+	public function __construct($wp_query, array $CPT = [])
25
+	{
26
+		if ($wp_query instanceof WP_Query) {
27
+			$WP_Query  = $wp_query;
28
+			$this->CPT = $CPT;
29
+		} else {
30
+			$WP_Query  = $wp_query['WP_Query'] ?? null;
31
+			$this->CPT = $wp_query['CPT'] ?? null;
32
+		}
33
+		// !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
34
+		// here's the list of available filters in the WP_Query object
35
+		// 'posts_where'
36
+		// 'posts_where_paged'
37
+		// 'posts_groupby'
38
+		// 'posts_join_paged'
39
+		// 'posts_orderby'
40
+		// 'posts_distinct'
41
+		// 'post_limits'
42
+		// 'posts_fields'
43
+		// 'posts_join'
44
+		$this->_add_filters();
45
+		if ($WP_Query instanceof WP_Query) {
46
+			$WP_Query->is_espresso_event_single   = is_singular()
47
+													&& isset($WP_Query->query->post_type)
48
+													&& $WP_Query->query->post_type === 'espresso_events';
49
+			$WP_Query->is_espresso_event_archive  = is_post_type_archive('espresso_events');
50
+			$WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
51
+		}
52
+	}
53
+
54
+
55
+	/**
56
+	 * When an instance of this class is created, we add our filters
57
+	 * (which will get removed in case the next call to get_posts ISN'T
58
+	 * for event CPTs)
59
+	 */
60
+	protected function _add_filters()
61
+	{
62
+		add_filter('posts_fields', [$this, 'posts_fields'], 1, 2);
63
+		add_filter('posts_join', [$this, 'posts_join'], 1, 2);
64
+		add_filter('posts_where', [$this, 'posts_where'], 10, 2);
65
+		// add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
66
+		add_filter('posts_orderby', [$this, 'posts_orderby'], 1, 2);
67
+		add_filter('posts_groupby', [$this, 'posts_groupby'], 1, 2);
68
+		add_action('posts_selection', [$this, 'remove_filters']);
69
+	}
70
+
71
+
72
+	/**
73
+	 * public access to _remove_filters()
74
+	 *
75
+	 * @since 4.9.63.p
76
+	 */
77
+	public function remove_filters()
78
+	{
79
+		$this->_remove_filters();
80
+	}
81
+
82
+
83
+	/**
84
+	 * Should eb called when the last filter or hook is fired for this CPT strategy.
85
+	 * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
86
+	 * we don't want to join to the datetime table when querying for venues, do we!?)
87
+	 */
88
+	protected function _remove_filters()
89
+	{
90
+		remove_filter('posts_fields', [$this, 'posts_fields'], 1);
91
+		remove_filter('posts_join', [$this, 'posts_join'], 1);
92
+		remove_filter('posts_where', [$this, 'posts_where']);
93
+		// remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
94
+		remove_filter('posts_orderby', [$this, 'posts_orderby'], 1);
95
+		remove_filter('posts_groupby', [$this, 'posts_groupby'], 1);
96
+		remove_action('posts_selection', [$this, 'remove_filters']);
97
+	}
98
+
99
+
100
+	/**
101
+	 * @param string        $SQL
102
+	 * @param WP_Query|null $wp_query
103
+	 * @return    string
104
+	 * @throws EE_Error
105
+	 */
106
+	public function posts_fields(string $SQL, ?WP_Query $wp_query): string
107
+	{
108
+		if (
109
+			$wp_query instanceof WP_Query
110
+			&& (
111
+				$wp_query->is_espresso_event_single
112
+				|| $wp_query->is_espresso_event_archive
113
+				|| $wp_query->is_espresso_event_taxonomy
114
+			)
115
+		) {
116
+			// adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
117
+			$SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
118
+			if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
119
+				// because we only want to retrieve the next upcoming datetime for each event:
120
+				// add something like:
121
+				// ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
122
+				// to WP Query SELECT statement
123
+				$SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
124
+			}
125
+		}
126
+		return $SQL;
127
+	}
128
+
129
+
130
+	/**
131
+	 * @param string        $SQL
132
+	 * @param WP_Query|null $wp_query
133
+	 * @return string
134
+	 * @throws EE_Error
135
+	 */
136
+	public function posts_join(string $SQL, ?WP_Query $wp_query): string
137
+	{
138
+		if (
139
+			$wp_query instanceof WP_Query
140
+			&& (
141
+				$wp_query->is_espresso_event_single
142
+				|| $wp_query->is_espresso_event_archive
143
+				|| $wp_query->is_espresso_event_taxonomy
144
+			)
145
+		) {
146
+			// adds something like:
147
+			// " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
148
+			// to WP Query JOIN statement
149
+			$SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
150
+					. '.ID = ' . EEM_Datetime::instance()->table() . '.'
151
+					. EEM_Event::instance()->primary_key_name() . ' ) ';
152
+		}
153
+		return $SQL;
154
+	}
155
+
156
+
157
+	/**
158
+	 * @param string        $SQL
159
+	 * @param WP_Query|null $wp_query
160
+	 * @return string
161
+	 * @throws EE_Error
162
+	 */
163
+	public function posts_where(string $SQL, ?WP_Query $wp_query): string
164
+	{
165
+		if (
166
+			$wp_query instanceof WP_Query
167
+			&& (
168
+				$wp_query->is_espresso_event_archive
169
+				|| $wp_query->is_espresso_event_taxonomy
170
+			)
171
+		) {
172
+			if (
173
+				! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
174
+				|| ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
175
+				|| ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
176
+			) {
177
+				$SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
178
+						. current_time('mysql', true) . "' ";
179
+			}
180
+		}
181
+		return $SQL;
182
+	}
183
+
184
+
185
+	/**
186
+	 * @param string        $SQL
187
+	 * @param WP_Query|null $wp_query
188
+	 * @return string
189
+	 */
190
+	public function posts_orderby(string $SQL, ?WP_Query $wp_query): string
191
+	{
192
+		if (
193
+			$wp_query instanceof WP_Query
194
+			&& (
195
+				$wp_query->is_espresso_event_archive
196
+				|| $wp_query->is_espresso_event_taxonomy
197
+			)
198
+		) {
199
+			$SQL = ' event_start_date ASC ';
200
+		}
201
+		return $SQL;
202
+	}
203
+
204
+
205
+	/**
206
+	 * @param string        $SQL
207
+	 * @param WP_Query|null $wp_query
208
+	 * @return string
209
+	 */
210
+	public function posts_groupby(string $SQL, ?WP_Query $wp_query): string
211
+	{
212
+		if (
213
+			$wp_query instanceof WP_Query
214
+			&& (
215
+				$wp_query->is_espresso_event_archive
216
+				|| $wp_query->is_espresso_event_taxonomy
217
+			)
218
+		) {
219
+			// TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
220
+			// we're joining to the datetimes table, where there can be MANY datetimes for a single event,
221
+			// but we want to only show each event only once
222
+			// (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
223
+			global $wpdb;
224
+			$SQL = $wpdb->posts . '.ID ';
225
+		}
226
+		return $SQL;
227
+	}
228
+
229
+
230
+	/**
231
+	 * @param array         $posts
232
+	 * @param WP_Query|null $wp_query
233
+	 * @return array
234
+	 */
235
+	public function the_posts(array $posts, ?WP_Query $wp_query): array
236
+	{
237
+		return $posts;
238
+	}
239
+
240
+
241
+	/**
242
+	 * @param mixed           $meta_value
243
+	 * @param int|string      $post_id
244
+	 * @param int|string      $meta_key
245
+	 * @param bool|int|string $single
246
+	 * @return mixed
247
+	 */
248
+	public function get_EE_post_type_metadata($meta_value, $post_id, $meta_key, $single)
249
+	{
250
+		return $meta_value;
251
+	}
252 252
 }
Please login to merge, or discard this patch.
core/services/address/CountrySubRegionDao.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
         $data = [];
81 81
         if (empty($this->countries)) {
82 82
             $this->data_version = $this->getCountrySubRegionDataVersion();
83
-            $data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
83
+            $data = $this->retrieveJsonData(self::REPO_URL.'countries.json');
84 84
         }
85 85
         if (empty($data)) {
86 86
             EE_Error::add_error(
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     private function processCountryData($CNT_ISO, $countries = array())
146 146
     {
147
-        if (! empty($countries)) {
147
+        if ( ! empty($countries)) {
148 148
             foreach ($countries as $key => $country) {
149 149
                 if (
150 150
                     $country instanceof stdClass
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
                     && ! empty($country->filename)
154 154
                 ) {
155 155
                     $country->sub_regions = $this->retrieveJsonData(
156
-                        self::REPO_URL . 'countries/' . $country->filename . '.json'
156
+                        self::REPO_URL.'countries/'.$country->filename.'.json'
157 157
                     );
158 158
                     return $this->saveSubRegionData($country, $country->sub_regions);
159 159
                 }
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
             foreach ($sub_regions as $sub_region) {
216 216
                 // remove country code from sub region code
217 217
                 $abbrev = str_replace(
218
-                    $country->code . '-',
218
+                    $country->code.'-',
219 219
                     '',
220 220
                     sanitize_text_field($sub_region->code)
221 221
                 );
Please login to merge, or discard this patch.
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -25,252 +25,252 @@
 block discarded – undo
25 25
  */
26 26
 class CountrySubRegionDao
27 27
 {
28
-    const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
28
+	const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
29 29
 
30
-    const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
30
+	const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
31 31
 
32
-    /**
33
-     * @var EEM_State $state_model
34
-     */
35
-    private $state_model;
32
+	/**
33
+	 * @var EEM_State $state_model
34
+	 */
35
+	private $state_model;
36 36
 
37
-    /**
38
-     * @var JsonValidator $json_validator
39
-     */
40
-    private $json_validator;
37
+	/**
38
+	 * @var JsonValidator $json_validator
39
+	 */
40
+	private $json_validator;
41 41
 
42
-    /**
43
-     * @var string $data_version
44
-     */
45
-    private $data_version;
42
+	/**
43
+	 * @var string $data_version
44
+	 */
45
+	private $data_version;
46 46
 
47
-    /**
48
-     * @var array $countries
49
-     */
50
-    private $countries = array();
47
+	/**
48
+	 * @var array $countries
49
+	 */
50
+	private $countries = array();
51 51
 
52 52
 
53
-    /**
54
-     * CountrySubRegionDao constructor.
55
-     *
56
-     * @param EEM_State     $state_model
57
-     * @param JsonValidator $json_validator
58
-     */
59
-    public function __construct(EEM_State $state_model, JsonValidator $json_validator)
60
-    {
61
-        $this->state_model = $state_model;
62
-        $this->json_validator = $json_validator;
63
-    }
53
+	/**
54
+	 * CountrySubRegionDao constructor.
55
+	 *
56
+	 * @param EEM_State     $state_model
57
+	 * @param JsonValidator $json_validator
58
+	 */
59
+	public function __construct(EEM_State $state_model, JsonValidator $json_validator)
60
+	{
61
+		$this->state_model = $state_model;
62
+		$this->json_validator = $json_validator;
63
+	}
64 64
 
65 65
 
66
-    /**
67
-     * @param EE_Country $country_object
68
-     * @return bool
69
-     * @throws EE_Error
70
-     * @throws InvalidArgumentException
71
-     * @throws InvalidDataTypeException
72
-     * @throws InvalidInterfaceException
73
-     * @throws ReflectionException
74
-     */
75
-    public function saveCountrySubRegions(EE_Country $country_object)
76
-    {
77
-        $CNT_ISO = $country_object->ID();
78
-        $has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
79
-        $data = [];
80
-        if (empty($this->countries)) {
81
-            $this->data_version = $this->getCountrySubRegionDataVersion();
82
-            $data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
83
-        }
84
-        if (empty($data)) {
85
-            EE_Error::add_error(
86
-                'Country Subregion Data could not be retrieved',
87
-                __FILE__,
88
-                __METHOD__,
89
-                __LINE__
90
-            );
91
-        }
92
-        if (
93
-            ! $has_sub_regions
94
-            || (isset($data->version) && version_compare($data->version, $this->data_version))
95
-        ) {
96
-            if (
97
-                isset($data->countries)
98
-                && $this->processCountryData($CNT_ISO, $data->countries) > 0
99
-            ) {
100
-                $this->countries = $data->countries;
101
-                $this->updateCountrySubRegionDataVersion($data->version);
102
-                return true;
103
-            }
104
-        }
105
-        return false;
106
-    }
66
+	/**
67
+	 * @param EE_Country $country_object
68
+	 * @return bool
69
+	 * @throws EE_Error
70
+	 * @throws InvalidArgumentException
71
+	 * @throws InvalidDataTypeException
72
+	 * @throws InvalidInterfaceException
73
+	 * @throws ReflectionException
74
+	 */
75
+	public function saveCountrySubRegions(EE_Country $country_object)
76
+	{
77
+		$CNT_ISO = $country_object->ID();
78
+		$has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
79
+		$data = [];
80
+		if (empty($this->countries)) {
81
+			$this->data_version = $this->getCountrySubRegionDataVersion();
82
+			$data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
83
+		}
84
+		if (empty($data)) {
85
+			EE_Error::add_error(
86
+				'Country Subregion Data could not be retrieved',
87
+				__FILE__,
88
+				__METHOD__,
89
+				__LINE__
90
+			);
91
+		}
92
+		if (
93
+			! $has_sub_regions
94
+			|| (isset($data->version) && version_compare($data->version, $this->data_version))
95
+		) {
96
+			if (
97
+				isset($data->countries)
98
+				&& $this->processCountryData($CNT_ISO, $data->countries) > 0
99
+			) {
100
+				$this->countries = $data->countries;
101
+				$this->updateCountrySubRegionDataVersion($data->version);
102
+				return true;
103
+			}
104
+		}
105
+		return false;
106
+	}
107 107
 
108 108
 
109
-    /**
110
-     * @since 4.9.70.p
111
-     * @return string
112
-     */
113
-    private function getCountrySubRegionDataVersion()
114
-    {
115
-        return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
116
-    }
109
+	/**
110
+	 * @since 4.9.70.p
111
+	 * @return string
112
+	 */
113
+	private function getCountrySubRegionDataVersion()
114
+	{
115
+		return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * @param string $version
121
-     */
122
-    private function updateCountrySubRegionDataVersion($version = '')
123
-    {
124
-        // add version option if it has never been added before, or update existing
125
-        if ($this->data_version === null) {
126
-            add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
127
-        } else {
128
-            update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
129
-        }
130
-    }
119
+	/**
120
+	 * @param string $version
121
+	 */
122
+	private function updateCountrySubRegionDataVersion($version = '')
123
+	{
124
+		// add version option if it has never been added before, or update existing
125
+		if ($this->data_version === null) {
126
+			add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
127
+		} else {
128
+			update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
129
+		}
130
+	}
131 131
 
132 132
 
133
-    /**
134
-     * @param string $CNT_ISO
135
-     * @param array  $countries
136
-     * @return int
137
-     * @throws EE_Error
138
-     * @throws InvalidArgumentException
139
-     * @throws InvalidDataTypeException
140
-     * @throws InvalidInterfaceException
141
-     * @throws ReflectionException
142
-     * @since 4.9.70.p
143
-     */
144
-    private function processCountryData($CNT_ISO, $countries = array())
145
-    {
146
-        if (! empty($countries)) {
147
-            foreach ($countries as $key => $country) {
148
-                if (
149
-                    $country instanceof stdClass
150
-                    && $country->code === $CNT_ISO
151
-                    && empty($country->sub_regions)
152
-                    && ! empty($country->filename)
153
-                ) {
154
-                    $country->sub_regions = $this->retrieveJsonData(
155
-                        self::REPO_URL . 'countries/' . $country->filename . '.json'
156
-                    );
157
-                    return $this->saveSubRegionData($country, $country->sub_regions);
158
-                }
159
-            }
160
-        }
161
-        return 0;
162
-    }
133
+	/**
134
+	 * @param string $CNT_ISO
135
+	 * @param array  $countries
136
+	 * @return int
137
+	 * @throws EE_Error
138
+	 * @throws InvalidArgumentException
139
+	 * @throws InvalidDataTypeException
140
+	 * @throws InvalidInterfaceException
141
+	 * @throws ReflectionException
142
+	 * @since 4.9.70.p
143
+	 */
144
+	private function processCountryData($CNT_ISO, $countries = array())
145
+	{
146
+		if (! empty($countries)) {
147
+			foreach ($countries as $key => $country) {
148
+				if (
149
+					$country instanceof stdClass
150
+					&& $country->code === $CNT_ISO
151
+					&& empty($country->sub_regions)
152
+					&& ! empty($country->filename)
153
+				) {
154
+					$country->sub_regions = $this->retrieveJsonData(
155
+						self::REPO_URL . 'countries/' . $country->filename . '.json'
156
+					);
157
+					return $this->saveSubRegionData($country, $country->sub_regions);
158
+				}
159
+			}
160
+		}
161
+		return 0;
162
+	}
163 163
 
164 164
 
165
-    /**
166
-     * @param string $url
167
-     * @return array
168
-     */
169
-    private function retrieveJsonData($url)
170
-    {
171
-        if (empty($url)) {
172
-            EE_Error::add_error(
173
-                'No URL was provided!',
174
-                __FILE__,
175
-                __METHOD__,
176
-                __LINE__
177
-            );
178
-            return array();
179
-        }
180
-        $request = wp_safe_remote_get($url);
181
-        if ($request instanceof WP_Error) {
182
-            EE_Error::add_error(
183
-                $request->get_error_message(),
184
-                __FILE__,
185
-                __METHOD__,
186
-                __LINE__
187
-            );
188
-            return array();
189
-        }
190
-        $body = wp_remote_retrieve_body($request);
191
-        $json = json_decode($body);
192
-        if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
193
-            return $json;
194
-        }
195
-        return array();
196
-    }
165
+	/**
166
+	 * @param string $url
167
+	 * @return array
168
+	 */
169
+	private function retrieveJsonData($url)
170
+	{
171
+		if (empty($url)) {
172
+			EE_Error::add_error(
173
+				'No URL was provided!',
174
+				__FILE__,
175
+				__METHOD__,
176
+				__LINE__
177
+			);
178
+			return array();
179
+		}
180
+		$request = wp_safe_remote_get($url);
181
+		if ($request instanceof WP_Error) {
182
+			EE_Error::add_error(
183
+				$request->get_error_message(),
184
+				__FILE__,
185
+				__METHOD__,
186
+				__LINE__
187
+			);
188
+			return array();
189
+		}
190
+		$body = wp_remote_retrieve_body($request);
191
+		$json = json_decode($body);
192
+		if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
193
+			return $json;
194
+		}
195
+		return array();
196
+	}
197 197
 
198 198
 
199
-    /**
200
-     * @param stdClass $country
201
-     * @param array    $sub_regions
202
-     * @return int
203
-     * @throws EE_Error
204
-     * @throws InvalidArgumentException
205
-     * @throws InvalidDataTypeException
206
-     * @throws InvalidInterfaceException
207
-     * @throws ReflectionException
208
-     */
209
-    private function saveSubRegionData(stdClass $country, $sub_regions = array())
210
-    {
211
-        $results = 0;
212
-        if (is_array($sub_regions)) {
213
-            $existing_sub_regions = $this->getExistingStateAbbreviations($country->code);
214
-            foreach ($sub_regions as $sub_region) {
215
-                // remove country code from sub region code
216
-                $abbrev = str_replace(
217
-                    $country->code . '-',
218
-                    '',
219
-                    sanitize_text_field($sub_region->code)
220
-                );
221
-                // but NOT if sub region code results in only a number
222
-                if (absint($abbrev) !== 0) {
223
-                    $abbrev = sanitize_text_field($sub_region->code);
224
-                }
225
-                if (
226
-                    ! in_array($abbrev, $existing_sub_regions, true)
227
-                    && $this->state_model->insert(
228
-                        [
229
-                            // STA_ID CNT_ISO STA_abbrev STA_name STA_active
230
-                            'CNT_ISO'    => $country->code,
231
-                            'STA_abbrev' => $abbrev,
232
-                            'STA_name'   => sanitize_text_field($sub_region->name),
233
-                            'STA_active' => 1,
234
-                        ]
235
-                    )
236
-                ) {
237
-                    $results++;
238
-                }
239
-            }
240
-        }
241
-        return $results;
242
-    }
199
+	/**
200
+	 * @param stdClass $country
201
+	 * @param array    $sub_regions
202
+	 * @return int
203
+	 * @throws EE_Error
204
+	 * @throws InvalidArgumentException
205
+	 * @throws InvalidDataTypeException
206
+	 * @throws InvalidInterfaceException
207
+	 * @throws ReflectionException
208
+	 */
209
+	private function saveSubRegionData(stdClass $country, $sub_regions = array())
210
+	{
211
+		$results = 0;
212
+		if (is_array($sub_regions)) {
213
+			$existing_sub_regions = $this->getExistingStateAbbreviations($country->code);
214
+			foreach ($sub_regions as $sub_region) {
215
+				// remove country code from sub region code
216
+				$abbrev = str_replace(
217
+					$country->code . '-',
218
+					'',
219
+					sanitize_text_field($sub_region->code)
220
+				);
221
+				// but NOT if sub region code results in only a number
222
+				if (absint($abbrev) !== 0) {
223
+					$abbrev = sanitize_text_field($sub_region->code);
224
+				}
225
+				if (
226
+					! in_array($abbrev, $existing_sub_regions, true)
227
+					&& $this->state_model->insert(
228
+						[
229
+							// STA_ID CNT_ISO STA_abbrev STA_name STA_active
230
+							'CNT_ISO'    => $country->code,
231
+							'STA_abbrev' => $abbrev,
232
+							'STA_name'   => sanitize_text_field($sub_region->name),
233
+							'STA_active' => 1,
234
+						]
235
+					)
236
+				) {
237
+					$results++;
238
+				}
239
+			}
240
+		}
241
+		return $results;
242
+	}
243 243
 
244 244
 
245
-    /**
246
-     * @param string $CNT_ISO
247
-     * @since 4.9.76.p
248
-     * @return array
249
-     * @throws EE_Error
250
-     * @throws InvalidArgumentException
251
-     * @throws InvalidDataTypeException
252
-     * @throws InvalidInterfaceException
253
-     * @throws ReflectionException
254
-     */
255
-    private function getExistingStateAbbreviations($CNT_ISO)
256
-    {
257
-        $existing_sub_region_IDs = [];
258
-        $existing_sub_regions = $this->state_model->get_all(array(
259
-            array(
260
-                'Country.CNT_ISO' => array(
261
-                    'IN',
262
-                    [$CNT_ISO]
263
-                )
264
-            ),
265
-            'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')
266
-        ));
267
-        if (is_array($existing_sub_regions)) {
268
-            foreach ($existing_sub_regions as $existing_sub_region) {
269
-                if ($existing_sub_region instanceof EE_State) {
270
-                    $existing_sub_region_IDs[] = $existing_sub_region->abbrev();
271
-                }
272
-            }
273
-        }
274
-        return $existing_sub_region_IDs;
275
-    }
245
+	/**
246
+	 * @param string $CNT_ISO
247
+	 * @since 4.9.76.p
248
+	 * @return array
249
+	 * @throws EE_Error
250
+	 * @throws InvalidArgumentException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws InvalidInterfaceException
253
+	 * @throws ReflectionException
254
+	 */
255
+	private function getExistingStateAbbreviations($CNT_ISO)
256
+	{
257
+		$existing_sub_region_IDs = [];
258
+		$existing_sub_regions = $this->state_model->get_all(array(
259
+			array(
260
+				'Country.CNT_ISO' => array(
261
+					'IN',
262
+					[$CNT_ISO]
263
+				)
264
+			),
265
+			'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')
266
+		));
267
+		if (is_array($existing_sub_regions)) {
268
+			foreach ($existing_sub_regions as $existing_sub_region) {
269
+				if ($existing_sub_region instanceof EE_State) {
270
+					$existing_sub_region_IDs[] = $existing_sub_region->abbrev();
271
+				}
272
+			}
273
+		}
274
+		return $existing_sub_region_IDs;
275
+	}
276 276
 }
Please login to merge, or discard this patch.
core/services/payment_methods/forms/PayPalSettingsForm.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -20,202 +20,202 @@
 block discarded – undo
20 20
  */
21 21
 class PayPalSettingsForm extends EE_Payment_Method_Form
22 22
 {
23
-    /**
24
-     * @var string of HTML being the help tab link
25
-     */
26
-    protected $helpTabLink;
23
+	/**
24
+	 * @var string of HTML being the help tab link
25
+	 */
26
+	protected $helpTabLink;
27 27
 
28
-    public function __construct(array $options_array = array(), $help_tab_link = '')
29
-    {
30
-        $this->helpTabLink = $help_tab_link;
31
-        $options_array = array_replace_recursive(
32
-            array(
33
-                'extra_meta_inputs' => array(
34
-                    'api_username' => new EE_Text_Input(
35
-                        array(
36
-                            'html_label_text' => sprintf(
37
-                                // translators: %s link to help doc
38
-                                esc_html__('API Username %s', 'event_espresso'),
39
-                                $help_tab_link
40
-                            ),
41
-                            'required'        => true,
42
-                        )
43
-                    ),
44
-                    'api_password' => new EE_Text_Input(
45
-                        array(
46
-                            'html_label_text' => sprintf(
47
-                                // translators: %s link to help doc
48
-                                esc_html__('API Password %s', 'event_espresso'),
49
-                                $help_tab_link
50
-                            ),
51
-                            'required'        => true,
52
-                        )
53
-                    ),
54
-                    'api_signature' => new EE_Text_Input(
55
-                        array(
56
-                            'html_label_text' => sprintf(
57
-                                // translators: %s link to help doc
58
-                                esc_html__('API Signature %s', 'event_espresso'),
59
-                                $help_tab_link
60
-                            ),
61
-                            'required'        => true,
62
-                        )
63
-                    ),
64
-                )
65
-            ),
66
-            $options_array
67
-        );
68
-        parent::__construct($options_array);
69
-    }
28
+	public function __construct(array $options_array = array(), $help_tab_link = '')
29
+	{
30
+		$this->helpTabLink = $help_tab_link;
31
+		$options_array = array_replace_recursive(
32
+			array(
33
+				'extra_meta_inputs' => array(
34
+					'api_username' => new EE_Text_Input(
35
+						array(
36
+							'html_label_text' => sprintf(
37
+								// translators: %s link to help doc
38
+								esc_html__('API Username %s', 'event_espresso'),
39
+								$help_tab_link
40
+							),
41
+							'required'        => true,
42
+						)
43
+					),
44
+					'api_password' => new EE_Text_Input(
45
+						array(
46
+							'html_label_text' => sprintf(
47
+								// translators: %s link to help doc
48
+								esc_html__('API Password %s', 'event_espresso'),
49
+								$help_tab_link
50
+							),
51
+							'required'        => true,
52
+						)
53
+					),
54
+					'api_signature' => new EE_Text_Input(
55
+						array(
56
+							'html_label_text' => sprintf(
57
+								// translators: %s link to help doc
58
+								esc_html__('API Signature %s', 'event_espresso'),
59
+								$help_tab_link
60
+							),
61
+							'required'        => true,
62
+						)
63
+					),
64
+				)
65
+			),
66
+			$options_array
67
+		);
68
+		parent::__construct($options_array);
69
+	}
70 70
 
71
-    /**
72
-     * Tests the the PayPal API credentials work ok
73
-     * @return string of an error using the credentials, otherwise, if the credentials work, returns a blank string
74
-     * @throws EE_Error
75
-     */
76
-    protected function checkForCredentialsErrors()
77
-    {
78
-        $request_params = array(
79
-            'METHOD'    => 'GetBalance',
80
-            'VERSION'   => '204.0',
81
-            'USER'      => $this->get_input_value('api_username'),
82
-            'PWD'       => $this->get_input_value('api_password'),
83
-            'SIGNATURE' => $this->get_input_value('api_signature'),
84
-        );
85
-        $gateway_url = $this->get_input_value('PMD_debug_mode')
86
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
87
-            : 'https://api-3t.paypal.com/nvp';
88
-        // Request Customer Details.
89
-        $response = wp_remote_post(
90
-            $gateway_url,
91
-            array(
92
-                'method'      => 'POST',
93
-                'timeout'     => 45,
94
-                'httpversion' => '1.1',
95
-                'cookies'     => array(),
96
-                'headers'     => array(),
97
-                'body'        => http_build_query($request_params, '', '&'),
98
-            )
99
-        );
100
-        if (is_wp_error($response) || empty($response['body'])) {
101
-            // If we got here then there was an error in this request.
102
-            // maybe is turned off. We don't know the credentials are invalid
103
-            EE_Error::add_error(
104
-                sprintf(
105
-                    // translators: %1$s Error message received from PayPal
106
-                    esc_html__(
107
-                        // @codingStandardsIgnoreStart
108
-                        'Your PayPal credentials could not be verified. The following error occurred while communicating with PayPal: %1$s',
109
-                        // @codingStandardsIgnoreEnd
110
-                        'event_espresso'
111
-                    ),
112
-                    $response->get_error_message()
113
-                ),
114
-                __FILE__,
115
-                __FUNCTION__,
116
-                __LINE__
117
-            );
118
-        }
119
-        $response_args = array();
120
-        parse_str(urldecode($response['body']), $response_args);
71
+	/**
72
+	 * Tests the the PayPal API credentials work ok
73
+	 * @return string of an error using the credentials, otherwise, if the credentials work, returns a blank string
74
+	 * @throws EE_Error
75
+	 */
76
+	protected function checkForCredentialsErrors()
77
+	{
78
+		$request_params = array(
79
+			'METHOD'    => 'GetBalance',
80
+			'VERSION'   => '204.0',
81
+			'USER'      => $this->get_input_value('api_username'),
82
+			'PWD'       => $this->get_input_value('api_password'),
83
+			'SIGNATURE' => $this->get_input_value('api_signature'),
84
+		);
85
+		$gateway_url = $this->get_input_value('PMD_debug_mode')
86
+			? 'https://api-3t.sandbox.paypal.com/nvp'
87
+			: 'https://api-3t.paypal.com/nvp';
88
+		// Request Customer Details.
89
+		$response = wp_remote_post(
90
+			$gateway_url,
91
+			array(
92
+				'method'      => 'POST',
93
+				'timeout'     => 45,
94
+				'httpversion' => '1.1',
95
+				'cookies'     => array(),
96
+				'headers'     => array(),
97
+				'body'        => http_build_query($request_params, '', '&'),
98
+			)
99
+		);
100
+		if (is_wp_error($response) || empty($response['body'])) {
101
+			// If we got here then there was an error in this request.
102
+			// maybe is turned off. We don't know the credentials are invalid
103
+			EE_Error::add_error(
104
+				sprintf(
105
+					// translators: %1$s Error message received from PayPal
106
+					esc_html__(
107
+						// @codingStandardsIgnoreStart
108
+						'Your PayPal credentials could not be verified. The following error occurred while communicating with PayPal: %1$s',
109
+						// @codingStandardsIgnoreEnd
110
+						'event_espresso'
111
+					),
112
+					$response->get_error_message()
113
+				),
114
+				__FILE__,
115
+				__FUNCTION__,
116
+				__LINE__
117
+			);
118
+		}
119
+		$response_args = array();
120
+		parse_str(urldecode($response['body']), $response_args);
121 121
 
122
-        if (empty($response_args['ACK'])) {
123
-            EE_Error::add_error(
124
-                esc_html__(
125
-                    'Your PayPal credentials could not be verified. Part of their response was missing.',
126
-                    'event_espresso'
127
-                ),
128
-                __FILE__,
129
-                __FUNCTION__,
130
-                __LINE__
131
-            );
132
-        }
133
-        if (
134
-            in_array(
135
-                $response_args['ACK'],
136
-                array(
137
-                'Success',
138
-                'SuccessWithWarning'
139
-                ),
140
-                true
141
-            )
142
-        ) {
143
-            return '';
144
-        } else {
145
-            return sprintf(
146
-                // translators: %1$s: PayPal response message, %2$s: PayPal response code
147
-                esc_html__(
148
-                    // @codingStandardsIgnoreStart
149
-                    'Your PayPal API credentials appear to be invalid. PayPal said "%1$s (%2$s)". Please see tips below.',
150
-                    // @codingStandardsIgnoreEnd
151
-                    'event_espresso'
152
-                ),
153
-                isset($response_args['L_LONGMESSAGE0'])
154
-                    ? $response_args['L_LONGMESSAGE0']
155
-                    : esc_html__('No error message received from PayPal', 'event_espresso'),
156
-                isset($response_args['L_ERRORCODE0']) ? $response_args['L_ERRORCODE0'] : 0
157
-            );
158
-        }
159
-    }
122
+		if (empty($response_args['ACK'])) {
123
+			EE_Error::add_error(
124
+				esc_html__(
125
+					'Your PayPal credentials could not be verified. Part of their response was missing.',
126
+					'event_espresso'
127
+				),
128
+				__FILE__,
129
+				__FUNCTION__,
130
+				__LINE__
131
+			);
132
+		}
133
+		if (
134
+			in_array(
135
+				$response_args['ACK'],
136
+				array(
137
+				'Success',
138
+				'SuccessWithWarning'
139
+				),
140
+				true
141
+			)
142
+		) {
143
+			return '';
144
+		} else {
145
+			return sprintf(
146
+				// translators: %1$s: PayPal response message, %2$s: PayPal response code
147
+				esc_html__(
148
+					// @codingStandardsIgnoreStart
149
+					'Your PayPal API credentials appear to be invalid. PayPal said "%1$s (%2$s)". Please see tips below.',
150
+					// @codingStandardsIgnoreEnd
151
+					'event_espresso'
152
+				),
153
+				isset($response_args['L_LONGMESSAGE0'])
154
+					? $response_args['L_LONGMESSAGE0']
155
+					: esc_html__('No error message received from PayPal', 'event_espresso'),
156
+				isset($response_args['L_ERRORCODE0']) ? $response_args['L_ERRORCODE0'] : 0
157
+			);
158
+		}
159
+	}
160 160
 
161
-    /**
162
-     * Gets the HTML to show the link to the help tab
163
-     * @return string
164
-     */
165
-    protected function helpTabLink()
166
-    {
167
-        return $this->helpTabLink;
168
-    }
161
+	/**
162
+	 * Gets the HTML to show the link to the help tab
163
+	 * @return string
164
+	 */
165
+	protected function helpTabLink()
166
+	{
167
+		return $this->helpTabLink;
168
+	}
169 169
 
170
-    /**
171
-     * Does the normal validation, but also verifies the PayPal API credentials work.
172
-     * If they don't, sets a validation error on the entire form, and adds validation errors (which are really more
173
-     * tips) on each of the inputs that could be the cause of the problem.
174
-     * @throws EE_Error
175
-     */
176
-    public function _validate()
177
-    {
178
-        parent::_validate();
179
-        $credentials_message = $this->checkForCredentialsErrors();
180
-        if ($credentials_message !== '') {
181
-            $this->add_validation_error($credentials_message);
182
-            $this->get_input('PMD_debug_mode')->add_validation_error(
183
-                esc_html__(
184
-                    // @codingStandardsIgnoreStart
185
-                    'If you are using PayPal Sandbox (test) credentials, Debug mode should be set to "Yes". Otherwise, if you are using live PayPal credentials, set this to "No".',
186
-                    // @codingStandardsIgnoreEnd
187
-                    'event_espresso'
188
-                )
189
-            );
190
-            $this->get_input('api_username')->add_validation_error(
191
-                sprintf(
192
-                    // translators: $1$s HTML for a link to the help tab
193
-                    esc_html__(
194
-                        'Are you sure this is your API username, not your login username? %1$s',
195
-                        'event_espresso'
196
-                    ),
197
-                    $this->helpTabLink()
198
-                )
199
-            );
200
-            $this->get_input('api_password')->add_validation_error(
201
-                sprintf(
202
-                    // translators: $1$s HTML for a link to the help tab
203
-                    esc_html__(
204
-                        'Are you sure this is your API password, not your login password? %1$s',
205
-                        'event_espresso'
206
-                    ),
207
-                    $this->helpTabLink()
208
-                )
209
-            );
210
-            $this->get_input('api_signature')->add_validation_error(
211
-                sprintf(
212
-                    // translators: $1$s HTML for a link to the help tab
213
-                    esc_html__('Please verify your API signature is correct. %1$s', 'event_espresso'),
214
-                    $this->helpTabLink()
215
-                )
216
-            );
217
-        }
218
-    }
170
+	/**
171
+	 * Does the normal validation, but also verifies the PayPal API credentials work.
172
+	 * If they don't, sets a validation error on the entire form, and adds validation errors (which are really more
173
+	 * tips) on each of the inputs that could be the cause of the problem.
174
+	 * @throws EE_Error
175
+	 */
176
+	public function _validate()
177
+	{
178
+		parent::_validate();
179
+		$credentials_message = $this->checkForCredentialsErrors();
180
+		if ($credentials_message !== '') {
181
+			$this->add_validation_error($credentials_message);
182
+			$this->get_input('PMD_debug_mode')->add_validation_error(
183
+				esc_html__(
184
+					// @codingStandardsIgnoreStart
185
+					'If you are using PayPal Sandbox (test) credentials, Debug mode should be set to "Yes". Otherwise, if you are using live PayPal credentials, set this to "No".',
186
+					// @codingStandardsIgnoreEnd
187
+					'event_espresso'
188
+				)
189
+			);
190
+			$this->get_input('api_username')->add_validation_error(
191
+				sprintf(
192
+					// translators: $1$s HTML for a link to the help tab
193
+					esc_html__(
194
+						'Are you sure this is your API username, not your login username? %1$s',
195
+						'event_espresso'
196
+					),
197
+					$this->helpTabLink()
198
+				)
199
+			);
200
+			$this->get_input('api_password')->add_validation_error(
201
+				sprintf(
202
+					// translators: $1$s HTML for a link to the help tab
203
+					esc_html__(
204
+						'Are you sure this is your API password, not your login password? %1$s',
205
+						'event_espresso'
206
+					),
207
+					$this->helpTabLink()
208
+				)
209
+			);
210
+			$this->get_input('api_signature')->add_validation_error(
211
+				sprintf(
212
+					// translators: $1$s HTML for a link to the help tab
213
+					esc_html__('Please verify your API signature is correct. %1$s', 'event_espresso'),
214
+					$this->helpTabLink()
215
+				)
216
+			);
217
+		}
218
+	}
219 219
 }
220 220
 // End of file PayPalSettingsForm.php
221 221
 // Location: ${NAMESPACE}/PayPalSettingsForm.php
Please login to merge, or discard this patch.
core/services/collections/CollectionDetails.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
      */
194 194
     protected function setCollectionInterface($collection_interface)
195 195
     {
196
-        if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
196
+        if ( ! (interface_exists($collection_interface) || class_exists($collection_interface))) {
197 197
             throw new InvalidInterfaceException($collection_interface);
198 198
         }
199 199
         $this->collection_interface = $collection_interface;
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      */
222 222
     protected function setCollectionName($collection_name)
223 223
     {
224
-        if (! is_string($collection_name)) {
224
+        if ( ! is_string($collection_name)) {
225 225
             throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
226 226
         }
227 227
         $this->collection_name = str_replace(
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
      */
282 282
     protected function setIdentifierCallback($identifier_callback = 'identifier')
283 283
     {
284
-        if (! is_string($identifier_callback)) {
284
+        if ( ! is_string($identifier_callback)) {
285 285
             throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
286 286
         }
287 287
         $this->identifier_callback = $identifier_callback;
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
         $this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
312 312
         // we know our default is a string, so if it's not a string now,
313 313
         // then that means the incoming parameter was something else
314
-        if (! is_string($this->file_mask)) {
314
+        if ( ! is_string($this->file_mask)) {
315 315
             throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
316 316
         }
317 317
     }
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
     public function setCollectionFQCNs($collection_FQCNs)
337 337
     {
338 338
         foreach ((array) $collection_FQCNs as $collection_FQCN) {
339
-            if (! empty($collection_FQCN)) {
339
+            if ( ! empty($collection_FQCN)) {
340 340
                 if (class_exists($collection_FQCN)) {
341 341
                     $this->collection_FQCNs[] = $collection_FQCN;
342 342
                 } else {
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
      */
359 359
     protected function getFQCNsFromPartialNamespace($partial_FQCN)
360 360
     {
361
-        if (! $this->file_locator instanceof FqcnLocator) {
361
+        if ( ! $this->file_locator instanceof FqcnLocator) {
362 362
             $this->file_locator = new FqcnLocator();
363 363
         }
364 364
         $this->file_locator->locate($partial_FQCN);
@@ -384,8 +384,8 @@  discard block
 block discarded – undo
384 384
     public function setCollectionPaths($collection_paths)
385 385
     {
386 386
         foreach ((array) $collection_paths as $collection_path) {
387
-            if (! empty($collection_path)) {
388
-                if (! is_readable($collection_path)) {
387
+            if ( ! empty($collection_path)) {
388
+                if ( ! is_readable($collection_path)) {
389 389
                     throw new InvalidFilePathException($collection_path);
390 390
                 }
391 391
                 $this->collection_paths[] = $collection_path;
Please login to merge, or discard this patch.
Indentation   +349 added lines, -349 removed lines patch added patch discarded remove patch
@@ -42,353 +42,353 @@
 block discarded – undo
42 42
  */
43 43
 class CollectionDetails implements CollectionDetailsInterface
44 44
 {
45
-    /**
46
-     * if $identifier_type is set to this,
47
-     * then the collection will use each object's spl_object_hash() as it's identifier
48
-     */
49
-    const ID_OBJECT_HASH = 'identifier-uses-spl-object-hash';
50
-
51
-    /**
52
-     * if $identifier_type is set to this,
53
-     * then the collection will use each object's class name as it's identifier
54
-     */
55
-    const ID_CLASS_NAME = 'identifier-uses-object-class-name';
56
-
57
-    /**
58
-     * if $identifier_type is set to this,
59
-     * then the collection will use the return value from a specified callback method on each object
60
-     */
61
-    const ID_CALLBACK_METHOD = 'identifier-uses-callback-method';
62
-
63
-    /**
64
-     * The interface used for controlling what gets added to the collection
65
-     *
66
-     * @var string $collection_interface
67
-     */
68
-    protected $collection_interface = '';
69
-
70
-    /**
71
-     * a unique name used to identify the collection in filter names
72
-     * supplied value is run through sanitize_title_with_dashes(),
73
-     * but then also converts dashes to underscores
74
-     *
75
-     * @var string $collection_name
76
-     */
77
-    protected $collection_name = '';
78
-
79
-    /**
80
-     * what the collection uses for the object identifier.
81
-     * corresponds to one of the class constants above.
82
-     * CollectionDetails::ID_OBJECT_HASH will use spl_object_hash( object ) for the identifier
83
-     * CollectionDetails::ID_CLASS_NAME will use get_class( object ) for the identifier
84
-     * CollectionDetails::ID_CALLBACK_METHOD will use a callback for the identifier
85
-     * defaults to using spl_object_hash() so that multiple objects of the same class can be added
86
-     *
87
-     * @var string $identifier_type
88
-     */
89
-    protected $identifier_type = CollectionDetails::ID_OBJECT_HASH;
90
-
91
-    /**
92
-     * the pattern applied to paths when searching for class files to add to the collection
93
-     * ie: "My_Awesome_*.class.php"
94
-     * defaults to "*.php"
95
-     *
96
-     * @var string $file_mask
97
-     */
98
-    protected $file_mask = '';
99
-
100
-    /**
101
-     * if the $identifier_type above is set to CollectionDetails::ID_CALLBACK_METHOD,
102
-     * then this specifies the method to use on each entity.
103
-     * If the callback method does not exist, then an exception will be thrown
104
-     *
105
-     * @var string $identifier_callback
106
-     */
107
-    protected $identifier_callback = '';
108
-
109
-    /**
110
-     * an array of Fully Qualified Class Names
111
-     *  for example:
112
-     *  $FQCNs = array(
113
-     *      '/Fully/Qualified/ClassNameA'
114
-     *      '/Fully/Qualified/Other/ClassNameB'
115
-     *  );
116
-     *
117
-     * @var array $collection_FQCNs
118
-     */
119
-    protected $collection_FQCNs = array();
120
-
121
-    /**
122
-     * an array of full server paths to folders containing files to be loaded into collection
123
-     *  for example:
124
-     *  $paths = array(
125
-     *      '/full/server/path/to/ClassNameA.ext.php' // for class ClassNameA
126
-     *      '/full/server/path/to/other/ClassNameB.php' // for class ClassNameB
127
-     *  );
128
-     *
129
-     * @var array $collection_paths
130
-     */
131
-    protected $collection_paths = array();
132
-
133
-    /**
134
-     * @var LocatorInterface $file_locator
135
-     */
136
-    protected $file_locator;
137
-
138
-
139
-    /**
140
-     * CollectionDetails constructor.
141
-     *
142
-     * @access public
143
-     * @param string           $collection_name
144
-     * @param string           $collection_interface
145
-     * @param array            $collection_FQCNs
146
-     * @param array            $collection_paths
147
-     * @param string           $file_mask
148
-     * @param string           $identifier_type
149
-     * @param string           $identifier_callback
150
-     * @param LocatorInterface $file_locator
151
-     * @throws CollectionDetailsException
152
-     */
153
-    public function __construct(
154
-        $collection_name,
155
-        $collection_interface,
156
-        array $collection_FQCNs = array(),
157
-        array $collection_paths = array(),
158
-        $file_mask = '',
159
-        $identifier_type = CollectionDetails::ID_OBJECT_HASH,
160
-        $identifier_callback = '',
161
-        LocatorInterface $file_locator = null
162
-    ) {
163
-        try {
164
-            $this->setCollectionName($collection_name);
165
-            $this->setCollectionInterface($collection_interface);
166
-            $this->setCollectionFQCNs($collection_FQCNs);
167
-            $this->setCollectionPaths($collection_paths);
168
-            $this->setFileMasks($file_mask);
169
-            $this->setIdentifierType($identifier_type);
170
-            $this->setIdentifierCallback($identifier_callback);
171
-            $this->file_locator = $file_locator;
172
-        } catch (Exception $exception) {
173
-            throw new CollectionDetailsException($exception);
174
-        }
175
-    }
176
-
177
-
178
-    /**
179
-     * @access public
180
-     * @return mixed
181
-     */
182
-    public function getCollectionInterface()
183
-    {
184
-        return $this->collection_interface;
185
-    }
186
-
187
-
188
-    /**
189
-     * @access protected
190
-     * @param string $collection_interface
191
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
192
-     */
193
-    protected function setCollectionInterface($collection_interface)
194
-    {
195
-        if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
196
-            throw new InvalidInterfaceException($collection_interface);
197
-        }
198
-        $this->collection_interface = $collection_interface;
199
-    }
200
-
201
-
202
-    /**
203
-     * the collection name will be used for creating dynamic filters
204
-     *
205
-     * @access public
206
-     * @return string
207
-     */
208
-    public function collectionName()
209
-    {
210
-        return $this->collection_name;
211
-    }
212
-
213
-
214
-    /**
215
-     * sanitizes collection name and converts spaces and dashes to underscores
216
-     *
217
-     * @access protected
218
-     * @param string $collection_name
219
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
220
-     */
221
-    protected function setCollectionName($collection_name)
222
-    {
223
-        if (! is_string($collection_name)) {
224
-            throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
225
-        }
226
-        $this->collection_name = str_replace(
227
-            '-',
228
-            '_',
229
-            sanitize_title_with_dashes($collection_name, '', 'save')
230
-        );
231
-    }
232
-
233
-
234
-    /**
235
-     * @access public
236
-     * @return string
237
-     */
238
-    public function identifierType()
239
-    {
240
-        return $this->identifier_type;
241
-    }
242
-
243
-
244
-    /**
245
-     * @access protected
246
-     * @param string $identifier_type
247
-     * @throws InvalidIdentifierException
248
-     */
249
-    protected function setIdentifierType($identifier_type)
250
-    {
251
-        if (
252
-            ! ($identifier_type === CollectionDetails::ID_CLASS_NAME
253
-               || $identifier_type === CollectionDetails::ID_OBJECT_HASH
254
-               || $identifier_type === CollectionDetails::ID_CALLBACK_METHOD
255
-            )
256
-        ) {
257
-            throw new InvalidIdentifierException(
258
-                $identifier_type,
259
-                'CollectionDetails::ID_CLASS_NAME or CollectionDetails::ID_OBJECT_HASH or CollectionDetails::ID_CALLBACK_METHOD'
260
-            );
261
-        }
262
-        $this->identifier_type = $identifier_type;
263
-    }
264
-
265
-
266
-    /**
267
-     * @access public
268
-     * @return string
269
-     */
270
-    public function identifierCallback()
271
-    {
272
-        return $this->identifier_callback;
273
-    }
274
-
275
-
276
-    /**
277
-     * @access protected
278
-     * @param string $identifier_callback
279
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
280
-     */
281
-    protected function setIdentifierCallback($identifier_callback = 'identifier')
282
-    {
283
-        if (! is_string($identifier_callback)) {
284
-            throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
285
-        }
286
-        $this->identifier_callback = $identifier_callback;
287
-    }
288
-
289
-
290
-    /**
291
-     * @access public
292
-     * @return string
293
-     */
294
-    public function getFileMask()
295
-    {
296
-        return $this->file_mask;
297
-    }
298
-
299
-
300
-    /**
301
-     * sets the file mask which is then used to filter what files get loaded
302
-     * when searching for classes to add to the collection. Defaults to '*.php'
303
-     *
304
-     * @access protected
305
-     * @param string $file_mask
306
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
307
-     */
308
-    protected function setFileMasks($file_mask)
309
-    {
310
-        $this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
311
-        // we know our default is a string, so if it's not a string now,
312
-        // then that means the incoming parameter was something else
313
-        if (! is_string($this->file_mask)) {
314
-            throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
315
-        }
316
-    }
317
-
318
-
319
-    /**
320
-     * @access public
321
-     * @return array
322
-     */
323
-    public function getCollectionFQCNs()
324
-    {
325
-        return $this->collection_FQCNs;
326
-    }
327
-
328
-
329
-    /**
330
-     * @access public
331
-     * @param string|array $collection_FQCNs
332
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
333
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
334
-     */
335
-    public function setCollectionFQCNs($collection_FQCNs)
336
-    {
337
-        foreach ((array) $collection_FQCNs as $collection_FQCN) {
338
-            if (! empty($collection_FQCN)) {
339
-                if (class_exists($collection_FQCN)) {
340
-                    $this->collection_FQCNs[] = $collection_FQCN;
341
-                } else {
342
-                    foreach ($this->getFQCNsFromPartialNamespace($collection_FQCN) as $FQCN) {
343
-                        $this->collection_FQCNs[] = $FQCN;
344
-                    }
345
-                }
346
-            }
347
-        }
348
-    }
349
-
350
-
351
-    /**
352
-     * @access protected
353
-     * @param  string $partial_FQCN
354
-     * @return array
355
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
356
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
357
-     */
358
-    protected function getFQCNsFromPartialNamespace($partial_FQCN)
359
-    {
360
-        if (! $this->file_locator instanceof FqcnLocator) {
361
-            $this->file_locator = new FqcnLocator();
362
-        }
363
-        $this->file_locator->locate($partial_FQCN);
364
-        return $this->file_locator->getFQCNs();
365
-    }
366
-
367
-
368
-    /**
369
-     * @access public
370
-     * @return array
371
-     */
372
-    public function getCollectionPaths()
373
-    {
374
-        return $this->collection_paths;
375
-    }
376
-
377
-
378
-    /**
379
-     * @access public
380
-     * @param string|array $collection_paths
381
-     * @throws \EventEspresso\core\exceptions\InvalidFilePathException
382
-     */
383
-    public function setCollectionPaths($collection_paths)
384
-    {
385
-        foreach ((array) $collection_paths as $collection_path) {
386
-            if (! empty($collection_path)) {
387
-                if (! is_readable($collection_path)) {
388
-                    throw new InvalidFilePathException($collection_path);
389
-                }
390
-                $this->collection_paths[] = $collection_path;
391
-            }
392
-        }
393
-    }
45
+	/**
46
+	 * if $identifier_type is set to this,
47
+	 * then the collection will use each object's spl_object_hash() as it's identifier
48
+	 */
49
+	const ID_OBJECT_HASH = 'identifier-uses-spl-object-hash';
50
+
51
+	/**
52
+	 * if $identifier_type is set to this,
53
+	 * then the collection will use each object's class name as it's identifier
54
+	 */
55
+	const ID_CLASS_NAME = 'identifier-uses-object-class-name';
56
+
57
+	/**
58
+	 * if $identifier_type is set to this,
59
+	 * then the collection will use the return value from a specified callback method on each object
60
+	 */
61
+	const ID_CALLBACK_METHOD = 'identifier-uses-callback-method';
62
+
63
+	/**
64
+	 * The interface used for controlling what gets added to the collection
65
+	 *
66
+	 * @var string $collection_interface
67
+	 */
68
+	protected $collection_interface = '';
69
+
70
+	/**
71
+	 * a unique name used to identify the collection in filter names
72
+	 * supplied value is run through sanitize_title_with_dashes(),
73
+	 * but then also converts dashes to underscores
74
+	 *
75
+	 * @var string $collection_name
76
+	 */
77
+	protected $collection_name = '';
78
+
79
+	/**
80
+	 * what the collection uses for the object identifier.
81
+	 * corresponds to one of the class constants above.
82
+	 * CollectionDetails::ID_OBJECT_HASH will use spl_object_hash( object ) for the identifier
83
+	 * CollectionDetails::ID_CLASS_NAME will use get_class( object ) for the identifier
84
+	 * CollectionDetails::ID_CALLBACK_METHOD will use a callback for the identifier
85
+	 * defaults to using spl_object_hash() so that multiple objects of the same class can be added
86
+	 *
87
+	 * @var string $identifier_type
88
+	 */
89
+	protected $identifier_type = CollectionDetails::ID_OBJECT_HASH;
90
+
91
+	/**
92
+	 * the pattern applied to paths when searching for class files to add to the collection
93
+	 * ie: "My_Awesome_*.class.php"
94
+	 * defaults to "*.php"
95
+	 *
96
+	 * @var string $file_mask
97
+	 */
98
+	protected $file_mask = '';
99
+
100
+	/**
101
+	 * if the $identifier_type above is set to CollectionDetails::ID_CALLBACK_METHOD,
102
+	 * then this specifies the method to use on each entity.
103
+	 * If the callback method does not exist, then an exception will be thrown
104
+	 *
105
+	 * @var string $identifier_callback
106
+	 */
107
+	protected $identifier_callback = '';
108
+
109
+	/**
110
+	 * an array of Fully Qualified Class Names
111
+	 *  for example:
112
+	 *  $FQCNs = array(
113
+	 *      '/Fully/Qualified/ClassNameA'
114
+	 *      '/Fully/Qualified/Other/ClassNameB'
115
+	 *  );
116
+	 *
117
+	 * @var array $collection_FQCNs
118
+	 */
119
+	protected $collection_FQCNs = array();
120
+
121
+	/**
122
+	 * an array of full server paths to folders containing files to be loaded into collection
123
+	 *  for example:
124
+	 *  $paths = array(
125
+	 *      '/full/server/path/to/ClassNameA.ext.php' // for class ClassNameA
126
+	 *      '/full/server/path/to/other/ClassNameB.php' // for class ClassNameB
127
+	 *  );
128
+	 *
129
+	 * @var array $collection_paths
130
+	 */
131
+	protected $collection_paths = array();
132
+
133
+	/**
134
+	 * @var LocatorInterface $file_locator
135
+	 */
136
+	protected $file_locator;
137
+
138
+
139
+	/**
140
+	 * CollectionDetails constructor.
141
+	 *
142
+	 * @access public
143
+	 * @param string           $collection_name
144
+	 * @param string           $collection_interface
145
+	 * @param array            $collection_FQCNs
146
+	 * @param array            $collection_paths
147
+	 * @param string           $file_mask
148
+	 * @param string           $identifier_type
149
+	 * @param string           $identifier_callback
150
+	 * @param LocatorInterface $file_locator
151
+	 * @throws CollectionDetailsException
152
+	 */
153
+	public function __construct(
154
+		$collection_name,
155
+		$collection_interface,
156
+		array $collection_FQCNs = array(),
157
+		array $collection_paths = array(),
158
+		$file_mask = '',
159
+		$identifier_type = CollectionDetails::ID_OBJECT_HASH,
160
+		$identifier_callback = '',
161
+		LocatorInterface $file_locator = null
162
+	) {
163
+		try {
164
+			$this->setCollectionName($collection_name);
165
+			$this->setCollectionInterface($collection_interface);
166
+			$this->setCollectionFQCNs($collection_FQCNs);
167
+			$this->setCollectionPaths($collection_paths);
168
+			$this->setFileMasks($file_mask);
169
+			$this->setIdentifierType($identifier_type);
170
+			$this->setIdentifierCallback($identifier_callback);
171
+			$this->file_locator = $file_locator;
172
+		} catch (Exception $exception) {
173
+			throw new CollectionDetailsException($exception);
174
+		}
175
+	}
176
+
177
+
178
+	/**
179
+	 * @access public
180
+	 * @return mixed
181
+	 */
182
+	public function getCollectionInterface()
183
+	{
184
+		return $this->collection_interface;
185
+	}
186
+
187
+
188
+	/**
189
+	 * @access protected
190
+	 * @param string $collection_interface
191
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
192
+	 */
193
+	protected function setCollectionInterface($collection_interface)
194
+	{
195
+		if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
196
+			throw new InvalidInterfaceException($collection_interface);
197
+		}
198
+		$this->collection_interface = $collection_interface;
199
+	}
200
+
201
+
202
+	/**
203
+	 * the collection name will be used for creating dynamic filters
204
+	 *
205
+	 * @access public
206
+	 * @return string
207
+	 */
208
+	public function collectionName()
209
+	{
210
+		return $this->collection_name;
211
+	}
212
+
213
+
214
+	/**
215
+	 * sanitizes collection name and converts spaces and dashes to underscores
216
+	 *
217
+	 * @access protected
218
+	 * @param string $collection_name
219
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
220
+	 */
221
+	protected function setCollectionName($collection_name)
222
+	{
223
+		if (! is_string($collection_name)) {
224
+			throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
225
+		}
226
+		$this->collection_name = str_replace(
227
+			'-',
228
+			'_',
229
+			sanitize_title_with_dashes($collection_name, '', 'save')
230
+		);
231
+	}
232
+
233
+
234
+	/**
235
+	 * @access public
236
+	 * @return string
237
+	 */
238
+	public function identifierType()
239
+	{
240
+		return $this->identifier_type;
241
+	}
242
+
243
+
244
+	/**
245
+	 * @access protected
246
+	 * @param string $identifier_type
247
+	 * @throws InvalidIdentifierException
248
+	 */
249
+	protected function setIdentifierType($identifier_type)
250
+	{
251
+		if (
252
+			! ($identifier_type === CollectionDetails::ID_CLASS_NAME
253
+			   || $identifier_type === CollectionDetails::ID_OBJECT_HASH
254
+			   || $identifier_type === CollectionDetails::ID_CALLBACK_METHOD
255
+			)
256
+		) {
257
+			throw new InvalidIdentifierException(
258
+				$identifier_type,
259
+				'CollectionDetails::ID_CLASS_NAME or CollectionDetails::ID_OBJECT_HASH or CollectionDetails::ID_CALLBACK_METHOD'
260
+			);
261
+		}
262
+		$this->identifier_type = $identifier_type;
263
+	}
264
+
265
+
266
+	/**
267
+	 * @access public
268
+	 * @return string
269
+	 */
270
+	public function identifierCallback()
271
+	{
272
+		return $this->identifier_callback;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @access protected
278
+	 * @param string $identifier_callback
279
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
280
+	 */
281
+	protected function setIdentifierCallback($identifier_callback = 'identifier')
282
+	{
283
+		if (! is_string($identifier_callback)) {
284
+			throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
285
+		}
286
+		$this->identifier_callback = $identifier_callback;
287
+	}
288
+
289
+
290
+	/**
291
+	 * @access public
292
+	 * @return string
293
+	 */
294
+	public function getFileMask()
295
+	{
296
+		return $this->file_mask;
297
+	}
298
+
299
+
300
+	/**
301
+	 * sets the file mask which is then used to filter what files get loaded
302
+	 * when searching for classes to add to the collection. Defaults to '*.php'
303
+	 *
304
+	 * @access protected
305
+	 * @param string $file_mask
306
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
307
+	 */
308
+	protected function setFileMasks($file_mask)
309
+	{
310
+		$this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
311
+		// we know our default is a string, so if it's not a string now,
312
+		// then that means the incoming parameter was something else
313
+		if (! is_string($this->file_mask)) {
314
+			throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
315
+		}
316
+	}
317
+
318
+
319
+	/**
320
+	 * @access public
321
+	 * @return array
322
+	 */
323
+	public function getCollectionFQCNs()
324
+	{
325
+		return $this->collection_FQCNs;
326
+	}
327
+
328
+
329
+	/**
330
+	 * @access public
331
+	 * @param string|array $collection_FQCNs
332
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
333
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
334
+	 */
335
+	public function setCollectionFQCNs($collection_FQCNs)
336
+	{
337
+		foreach ((array) $collection_FQCNs as $collection_FQCN) {
338
+			if (! empty($collection_FQCN)) {
339
+				if (class_exists($collection_FQCN)) {
340
+					$this->collection_FQCNs[] = $collection_FQCN;
341
+				} else {
342
+					foreach ($this->getFQCNsFromPartialNamespace($collection_FQCN) as $FQCN) {
343
+						$this->collection_FQCNs[] = $FQCN;
344
+					}
345
+				}
346
+			}
347
+		}
348
+	}
349
+
350
+
351
+	/**
352
+	 * @access protected
353
+	 * @param  string $partial_FQCN
354
+	 * @return array
355
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
356
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
357
+	 */
358
+	protected function getFQCNsFromPartialNamespace($partial_FQCN)
359
+	{
360
+		if (! $this->file_locator instanceof FqcnLocator) {
361
+			$this->file_locator = new FqcnLocator();
362
+		}
363
+		$this->file_locator->locate($partial_FQCN);
364
+		return $this->file_locator->getFQCNs();
365
+	}
366
+
367
+
368
+	/**
369
+	 * @access public
370
+	 * @return array
371
+	 */
372
+	public function getCollectionPaths()
373
+	{
374
+		return $this->collection_paths;
375
+	}
376
+
377
+
378
+	/**
379
+	 * @access public
380
+	 * @param string|array $collection_paths
381
+	 * @throws \EventEspresso\core\exceptions\InvalidFilePathException
382
+	 */
383
+	public function setCollectionPaths($collection_paths)
384
+	{
385
+		foreach ((array) $collection_paths as $collection_path) {
386
+			if (! empty($collection_path)) {
387
+				if (! is_readable($collection_path)) {
388
+					throw new InvalidFilePathException($collection_path);
389
+				}
390
+				$this->collection_paths[] = $collection_path;
391
+			}
392
+		}
393
+	}
394 394
 }
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public function setReturnUrl($return_url)
87 87
     {
88
-        if (! is_string($return_url)) {
88
+        if ( ! is_string($return_url)) {
89 89
             throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90 90
         }
91 91
         $this->return_url = $return_url;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     protected function getPersistentAdminNoticeCollection()
104 104
     {
105
-        if (! $this->notice_collection instanceof Collection) {
105
+        if ( ! $this->notice_collection instanceof Collection) {
106 106
             $this->notice_collection = new Collection(
107 107
                 'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108 108
             );
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
     protected function retrieveStoredNotices()
126 126
     {
127 127
         $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
-        if (! empty($persistent_admin_notices)) {
128
+        if ( ! empty($persistent_admin_notices)) {
129 129
             foreach ($persistent_admin_notices as $name => $details) {
130 130
                 if (is_array($details)) {
131 131
                     if (
@@ -247,14 +247,14 @@  discard block
 block discarded – undo
247 247
     {
248 248
         wp_register_script(
249 249
             'espresso_core',
250
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
250
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
251 251
             array('jquery'),
252 252
             EVENT_ESPRESSO_VERSION,
253 253
             true
254 254
         );
255 255
         wp_register_script(
256 256
             'ee_error_js',
257
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
257
+            EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
258 258
             array('espresso_core'),
259 259
             EVENT_ESPRESSO_VERSION,
260 260
             true
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
         // used in template
286 286
         $persistent_admin_notice_name = $persistent_admin_notice->getName();
287 287
         $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
288
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
288
+        require EE_TEMPLATES.'/notifications/persistent_admin_notice.template.php';
289 289
     }
290 290
 
291 291
 
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
     {
311 311
         $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
312 312
         $this->notice_collection = $this->getPersistentAdminNoticeCollection();
313
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
313
+        if ( ! empty($pan_name) && $this->notice_collection->has($pan_name)) {
314 314
             /** @var PersistentAdminNotice $persistent_admin_notice */
315 315
             $persistent_admin_notice = $this->notice_collection->get($pan_name);
316 316
             $persistent_admin_notice->setDismissed(true);
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
             foreach ($this->notice_collection as $persistent_admin_notice) {
361 361
                 // are we deleting this notice ?
362 362
                 if ($persistent_admin_notice->getPurge()) {
363
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
363
+                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
364 364
                 } else {
365 365
                     /** @var PersistentAdminNotice $persistent_admin_notice */
366
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
366
+                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
367 367
                         'message'     => $persistent_admin_notice->getMessage(),
368 368
                         'capability'  => $persistent_admin_notice->getCapability(),
369 369
                         'cap_context' => $persistent_admin_notice->getCapContext(),
Please login to merge, or discard this patch.
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -30,392 +30,392 @@
 block discarded – undo
30 30
  */
31 31
 class PersistentAdminNoticeManager
32 32
 {
33
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
-
35
-    /**
36
-     * @var Collection|PersistentAdminNotice[] $notice_collection
37
-     */
38
-    private $notice_collection;
39
-
40
-    /**
41
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
-     * persistent admin notice was displayed, and ultimately dismissed from.
43
-     *
44
-     * @var string $return_url
45
-     */
46
-    private $return_url;
47
-
48
-    /**
49
-     * @var CapabilitiesChecker $capabilities_checker
50
-     */
51
-    private $capabilities_checker;
52
-
53
-    /**
54
-     * @var RequestInterface $request
55
-     */
56
-    private $request;
57
-
58
-
59
-    /**
60
-     * PersistentAdminNoticeManager constructor
61
-     *
62
-     * @param CapabilitiesChecker $capabilities_checker
63
-     * @param RequestInterface    $request
64
-     * @param string              $return_url where to  redirect to after dismissing notices
65
-     * @throws InvalidDataTypeException
66
-     */
67
-    public function __construct(
68
-        CapabilitiesChecker $capabilities_checker,
69
-        RequestInterface $request,
70
-        string $return_url = ''
71
-    ) {
72
-        $this->setReturnUrl($return_url);
73
-        $this->capabilities_checker = $capabilities_checker;
74
-        $this->request = $request;
75
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
76
-        // and we want to retrieve and generate any nag notices at the last possible moment
77
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
78
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
79
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
80
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
81
-    }
82
-
83
-
84
-    /**
85
-     * @param string $return_url
86
-     * @throws InvalidDataTypeException
87
-     */
88
-    public function setReturnUrl($return_url)
89
-    {
90
-        if (! is_string($return_url)) {
91
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
92
-        }
93
-        $this->return_url = $return_url;
94
-    }
95
-
96
-
97
-    /**
98
-     * @return Collection
99
-     * @throws InvalidEntityException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws DomainException
103
-     * @throws DuplicateCollectionIdentifierException
104
-     */
105
-    protected function getPersistentAdminNoticeCollection()
106
-    {
107
-        if (! $this->notice_collection instanceof Collection) {
108
-            $this->notice_collection = new Collection(
109
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
110
-            );
111
-            $this->retrieveStoredNotices();
112
-            $this->registerNotices();
113
-        }
114
-        return $this->notice_collection;
115
-    }
116
-
117
-
118
-    /**
119
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
-     *
121
-     * @return void
122
-     * @throws InvalidEntityException
123
-     * @throws DomainException
124
-     * @throws InvalidDataTypeException
125
-     * @throws DuplicateCollectionIdentifierException
126
-     */
127
-    protected function retrieveStoredNotices()
128
-    {
129
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
130
-        if (! empty($persistent_admin_notices)) {
131
-            foreach ($persistent_admin_notices as $name => $details) {
132
-                if (is_array($details)) {
133
-                    if (
134
-                        ! isset(
135
-                            $details['message'],
136
-                            $details['capability'],
137
-                            $details['cap_context'],
138
-                            $details['dismissed']
139
-                        )
140
-                    ) {
141
-                        throw new DomainException(
142
-                            sprintf(
143
-                                esc_html__(
144
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $name
148
-                            )
149
-                        );
150
-                    }
151
-                    // new format for nag notices
152
-                    $this->notice_collection->add(
153
-                        new PersistentAdminNotice(
154
-                            $name,
155
-                            $details['message'],
156
-                            false,
157
-                            $details['capability'],
158
-                            $details['cap_context'],
159
-                            $details['dismissed']
160
-                        ),
161
-                        sanitize_key($name)
162
-                    );
163
-                } else {
164
-                    try {
165
-                        // old nag notices, that we want to convert to the new format
166
-                        $this->notice_collection->add(
167
-                            new PersistentAdminNotice(
168
-                                $name,
169
-                                (string) $details,
170
-                                false,
171
-                                '',
172
-                                '',
173
-                                empty($details)
174
-                            ),
175
-                            sanitize_key($name)
176
-                        );
177
-                    } catch (Exception $e) {
178
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
-                    }
180
-                }
181
-                // each notice will self register when the action hook in registerNotices is triggered
182
-            }
183
-        }
184
-    }
185
-
186
-
187
-    /**
188
-     * exposes the Persistent Admin Notice Collection via an action
189
-     * so that PersistentAdminNotice objects can be added and/or removed
190
-     * without compromising the actual collection like a filter would
191
-     */
192
-    protected function registerNotices()
193
-    {
194
-        do_action(
195
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
196
-            $this->notice_collection
197
-        );
198
-    }
199
-
200
-
201
-    /**
202
-     * @throws DomainException
203
-     * @throws InvalidClassException
204
-     * @throws InvalidDataTypeException
205
-     * @throws InvalidInterfaceException
206
-     * @throws InvalidEntityException
207
-     * @throws DuplicateCollectionIdentifierException
208
-     */
209
-    public function displayNotices()
210
-    {
211
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
212
-        if ($this->notice_collection->hasObjects()) {
213
-            $enqueue_assets = false;
214
-            // and display notices
215
-            foreach ($this->notice_collection as $persistent_admin_notice) {
216
-                /** @var PersistentAdminNotice $persistent_admin_notice */
217
-                // don't display notices that have already been dismissed
218
-                if ($persistent_admin_notice->getDismissed()) {
219
-                    continue;
220
-                }
221
-                try {
222
-                    $this->capabilities_checker->processCapCheck(
223
-                        $persistent_admin_notice->getCapCheck()
224
-                    );
225
-                } catch (InsufficientPermissionsException $e) {
226
-                    // user does not have required cap, so skip to next notice
227
-                    // and just eat the exception - nom nom nom nom
228
-                    continue;
229
-                }
230
-                if ($persistent_admin_notice->getMessage() === '') {
231
-                    continue;
232
-                }
233
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
234
-                $enqueue_assets = true;
235
-            }
236
-            if ($enqueue_assets) {
237
-                $this->enqueueAssets();
238
-            }
239
-        }
240
-    }
241
-
242
-
243
-    /**
244
-     * does what it's named
245
-     *
246
-     * @return void
247
-     */
248
-    public function enqueueAssets()
249
-    {
250
-        wp_register_script(
251
-            'espresso_core',
252
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
253
-            array('jquery'),
254
-            EVENT_ESPRESSO_VERSION,
255
-            true
256
-        );
257
-        wp_register_script(
258
-            'ee_error_js',
259
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
260
-            array('espresso_core'),
261
-            EVENT_ESPRESSO_VERSION,
262
-            true
263
-        );
264
-        wp_localize_script(
265
-            'ee_error_js',
266
-            'ee_dismiss',
267
-            array(
268
-                'return_url'    => urlencode($this->return_url),
269
-                'ajax_url'      => WP_AJAX_URL,
270
-                'unknown_error' => wp_strip_all_tags(
271
-                    __(
272
-                        'An unknown error has occurred on the server while attempting to dismiss this notice.',
273
-                        'event_espresso'
274
-                    )
275
-                ),
276
-            )
277
-        );
278
-        wp_enqueue_script('ee_error_js');
279
-    }
280
-
281
-
282
-    /**
283
-     * displayPersistentAdminNoticeHtml
284
-     *
285
-     * @param  PersistentAdminNotice $persistent_admin_notice
286
-     */
287
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
288
-    {
289
-        // used in template
290
-        $persistent_admin_notice_name = $persistent_admin_notice->getName();
291
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
292
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
293
-    }
294
-
295
-
296
-    /**
297
-     * dismissNotice
298
-     *
299
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
300
-     * @param bool   $purge    if true, then delete it from the db
301
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
302
-     * @return void
303
-     * @throws InvalidEntityException
304
-     * @throws InvalidInterfaceException
305
-     * @throws InvalidDataTypeException
306
-     * @throws DomainException
307
-     * @throws InvalidArgumentException
308
-     * @throws InvalidArgumentException
309
-     * @throws InvalidArgumentException
310
-     * @throws InvalidArgumentException
311
-     * @throws DuplicateCollectionIdentifierException
312
-     */
313
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
314
-    {
315
-        $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
316
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
317
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
318
-            /** @var PersistentAdminNotice $persistent_admin_notice */
319
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
320
-            $persistent_admin_notice->setDismissed(true);
321
-            $persistent_admin_notice->setPurge($purge);
322
-            $this->saveNotices();
323
-        }
324
-        if ($return) {
325
-            return;
326
-        }
327
-        if ($this->request->isAjax()) {
328
-            // grab any notices and concatenate into string
329
-            echo wp_json_encode(
330
-                array(
331
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
332
-                )
333
-            );
334
-            exit();
335
-        }
336
-        // save errors to a transient to be displayed on next request (after redirect)
337
-        EE_Error::get_notices(false, true);
338
-        wp_safe_redirect(
339
-            urldecode(
340
-                $this->request->getRequestParam('return_url', '')
341
-            )
342
-        );
343
-    }
344
-
345
-
346
-    /**
347
-     * saveNotices
348
-     *
349
-     * @throws DomainException
350
-     * @throws InvalidDataTypeException
351
-     * @throws InvalidInterfaceException
352
-     * @throws InvalidEntityException
353
-     * @throws DuplicateCollectionIdentifierException
354
-     */
355
-    public function saveNotices()
356
-    {
357
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
358
-        if ($this->notice_collection->hasObjects()) {
359
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
360
-            // maybe initialize persistent_admin_notices
361
-            if (empty($persistent_admin_notices)) {
362
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
363
-            }
364
-            foreach ($this->notice_collection as $persistent_admin_notice) {
365
-                // are we deleting this notice ?
366
-                if ($persistent_admin_notice->getPurge()) {
367
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
368
-                } else {
369
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
370
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
371
-                        'message'     => $persistent_admin_notice->getMessage(),
372
-                        'capability'  => $persistent_admin_notice->getCapability(),
373
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
374
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
375
-                    );
376
-                }
377
-            }
378
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
379
-        }
380
-    }
381
-
382
-
383
-    /**
384
-     * @throws DomainException
385
-     * @throws InvalidDataTypeException
386
-     * @throws InvalidEntityException
387
-     * @throws InvalidInterfaceException
388
-     * @throws DuplicateCollectionIdentifierException
389
-     */
390
-    public function registerAndSaveNotices()
391
-    {
392
-        $this->getPersistentAdminNoticeCollection();
393
-        $this->registerNotices();
394
-        $this->saveNotices();
395
-        add_filter(
396
-            'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
397
-            '__return_true'
398
-        );
399
-    }
400
-
401
-
402
-    /**
403
-     * @throws DomainException
404
-     * @throws InvalidDataTypeException
405
-     * @throws InvalidEntityException
406
-     * @throws InvalidInterfaceException
407
-     * @throws InvalidArgumentException
408
-     * @throws DuplicateCollectionIdentifierException
409
-     */
410
-    public static function loadRegisterAndSaveNotices()
411
-    {
412
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
413
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
414
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
415
-        );
416
-        // if shutdown has already run, then call registerAndSaveNotices() manually
417
-        if (did_action('shutdown')) {
418
-            $persistent_admin_notice_manager->registerAndSaveNotices();
419
-        }
420
-    }
33
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
+
35
+	/**
36
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
37
+	 */
38
+	private $notice_collection;
39
+
40
+	/**
41
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
+	 * persistent admin notice was displayed, and ultimately dismissed from.
43
+	 *
44
+	 * @var string $return_url
45
+	 */
46
+	private $return_url;
47
+
48
+	/**
49
+	 * @var CapabilitiesChecker $capabilities_checker
50
+	 */
51
+	private $capabilities_checker;
52
+
53
+	/**
54
+	 * @var RequestInterface $request
55
+	 */
56
+	private $request;
57
+
58
+
59
+	/**
60
+	 * PersistentAdminNoticeManager constructor
61
+	 *
62
+	 * @param CapabilitiesChecker $capabilities_checker
63
+	 * @param RequestInterface    $request
64
+	 * @param string              $return_url where to  redirect to after dismissing notices
65
+	 * @throws InvalidDataTypeException
66
+	 */
67
+	public function __construct(
68
+		CapabilitiesChecker $capabilities_checker,
69
+		RequestInterface $request,
70
+		string $return_url = ''
71
+	) {
72
+		$this->setReturnUrl($return_url);
73
+		$this->capabilities_checker = $capabilities_checker;
74
+		$this->request = $request;
75
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
76
+		// and we want to retrieve and generate any nag notices at the last possible moment
77
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
78
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
79
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
80
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
81
+	}
82
+
83
+
84
+	/**
85
+	 * @param string $return_url
86
+	 * @throws InvalidDataTypeException
87
+	 */
88
+	public function setReturnUrl($return_url)
89
+	{
90
+		if (! is_string($return_url)) {
91
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
92
+		}
93
+		$this->return_url = $return_url;
94
+	}
95
+
96
+
97
+	/**
98
+	 * @return Collection
99
+	 * @throws InvalidEntityException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws DomainException
103
+	 * @throws DuplicateCollectionIdentifierException
104
+	 */
105
+	protected function getPersistentAdminNoticeCollection()
106
+	{
107
+		if (! $this->notice_collection instanceof Collection) {
108
+			$this->notice_collection = new Collection(
109
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
110
+			);
111
+			$this->retrieveStoredNotices();
112
+			$this->registerNotices();
113
+		}
114
+		return $this->notice_collection;
115
+	}
116
+
117
+
118
+	/**
119
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
+	 *
121
+	 * @return void
122
+	 * @throws InvalidEntityException
123
+	 * @throws DomainException
124
+	 * @throws InvalidDataTypeException
125
+	 * @throws DuplicateCollectionIdentifierException
126
+	 */
127
+	protected function retrieveStoredNotices()
128
+	{
129
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
130
+		if (! empty($persistent_admin_notices)) {
131
+			foreach ($persistent_admin_notices as $name => $details) {
132
+				if (is_array($details)) {
133
+					if (
134
+						! isset(
135
+							$details['message'],
136
+							$details['capability'],
137
+							$details['cap_context'],
138
+							$details['dismissed']
139
+						)
140
+					) {
141
+						throw new DomainException(
142
+							sprintf(
143
+								esc_html__(
144
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
+									'event_espresso'
146
+								),
147
+								$name
148
+							)
149
+						);
150
+					}
151
+					// new format for nag notices
152
+					$this->notice_collection->add(
153
+						new PersistentAdminNotice(
154
+							$name,
155
+							$details['message'],
156
+							false,
157
+							$details['capability'],
158
+							$details['cap_context'],
159
+							$details['dismissed']
160
+						),
161
+						sanitize_key($name)
162
+					);
163
+				} else {
164
+					try {
165
+						// old nag notices, that we want to convert to the new format
166
+						$this->notice_collection->add(
167
+							new PersistentAdminNotice(
168
+								$name,
169
+								(string) $details,
170
+								false,
171
+								'',
172
+								'',
173
+								empty($details)
174
+							),
175
+							sanitize_key($name)
176
+						);
177
+					} catch (Exception $e) {
178
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
+					}
180
+				}
181
+				// each notice will self register when the action hook in registerNotices is triggered
182
+			}
183
+		}
184
+	}
185
+
186
+
187
+	/**
188
+	 * exposes the Persistent Admin Notice Collection via an action
189
+	 * so that PersistentAdminNotice objects can be added and/or removed
190
+	 * without compromising the actual collection like a filter would
191
+	 */
192
+	protected function registerNotices()
193
+	{
194
+		do_action(
195
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
196
+			$this->notice_collection
197
+		);
198
+	}
199
+
200
+
201
+	/**
202
+	 * @throws DomainException
203
+	 * @throws InvalidClassException
204
+	 * @throws InvalidDataTypeException
205
+	 * @throws InvalidInterfaceException
206
+	 * @throws InvalidEntityException
207
+	 * @throws DuplicateCollectionIdentifierException
208
+	 */
209
+	public function displayNotices()
210
+	{
211
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
212
+		if ($this->notice_collection->hasObjects()) {
213
+			$enqueue_assets = false;
214
+			// and display notices
215
+			foreach ($this->notice_collection as $persistent_admin_notice) {
216
+				/** @var PersistentAdminNotice $persistent_admin_notice */
217
+				// don't display notices that have already been dismissed
218
+				if ($persistent_admin_notice->getDismissed()) {
219
+					continue;
220
+				}
221
+				try {
222
+					$this->capabilities_checker->processCapCheck(
223
+						$persistent_admin_notice->getCapCheck()
224
+					);
225
+				} catch (InsufficientPermissionsException $e) {
226
+					// user does not have required cap, so skip to next notice
227
+					// and just eat the exception - nom nom nom nom
228
+					continue;
229
+				}
230
+				if ($persistent_admin_notice->getMessage() === '') {
231
+					continue;
232
+				}
233
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
234
+				$enqueue_assets = true;
235
+			}
236
+			if ($enqueue_assets) {
237
+				$this->enqueueAssets();
238
+			}
239
+		}
240
+	}
241
+
242
+
243
+	/**
244
+	 * does what it's named
245
+	 *
246
+	 * @return void
247
+	 */
248
+	public function enqueueAssets()
249
+	{
250
+		wp_register_script(
251
+			'espresso_core',
252
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
253
+			array('jquery'),
254
+			EVENT_ESPRESSO_VERSION,
255
+			true
256
+		);
257
+		wp_register_script(
258
+			'ee_error_js',
259
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
260
+			array('espresso_core'),
261
+			EVENT_ESPRESSO_VERSION,
262
+			true
263
+		);
264
+		wp_localize_script(
265
+			'ee_error_js',
266
+			'ee_dismiss',
267
+			array(
268
+				'return_url'    => urlencode($this->return_url),
269
+				'ajax_url'      => WP_AJAX_URL,
270
+				'unknown_error' => wp_strip_all_tags(
271
+					__(
272
+						'An unknown error has occurred on the server while attempting to dismiss this notice.',
273
+						'event_espresso'
274
+					)
275
+				),
276
+			)
277
+		);
278
+		wp_enqueue_script('ee_error_js');
279
+	}
280
+
281
+
282
+	/**
283
+	 * displayPersistentAdminNoticeHtml
284
+	 *
285
+	 * @param  PersistentAdminNotice $persistent_admin_notice
286
+	 */
287
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
288
+	{
289
+		// used in template
290
+		$persistent_admin_notice_name = $persistent_admin_notice->getName();
291
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
292
+		require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
293
+	}
294
+
295
+
296
+	/**
297
+	 * dismissNotice
298
+	 *
299
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
300
+	 * @param bool   $purge    if true, then delete it from the db
301
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
302
+	 * @return void
303
+	 * @throws InvalidEntityException
304
+	 * @throws InvalidInterfaceException
305
+	 * @throws InvalidDataTypeException
306
+	 * @throws DomainException
307
+	 * @throws InvalidArgumentException
308
+	 * @throws InvalidArgumentException
309
+	 * @throws InvalidArgumentException
310
+	 * @throws InvalidArgumentException
311
+	 * @throws DuplicateCollectionIdentifierException
312
+	 */
313
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
314
+	{
315
+		$pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
316
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
317
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
318
+			/** @var PersistentAdminNotice $persistent_admin_notice */
319
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
320
+			$persistent_admin_notice->setDismissed(true);
321
+			$persistent_admin_notice->setPurge($purge);
322
+			$this->saveNotices();
323
+		}
324
+		if ($return) {
325
+			return;
326
+		}
327
+		if ($this->request->isAjax()) {
328
+			// grab any notices and concatenate into string
329
+			echo wp_json_encode(
330
+				array(
331
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
332
+				)
333
+			);
334
+			exit();
335
+		}
336
+		// save errors to a transient to be displayed on next request (after redirect)
337
+		EE_Error::get_notices(false, true);
338
+		wp_safe_redirect(
339
+			urldecode(
340
+				$this->request->getRequestParam('return_url', '')
341
+			)
342
+		);
343
+	}
344
+
345
+
346
+	/**
347
+	 * saveNotices
348
+	 *
349
+	 * @throws DomainException
350
+	 * @throws InvalidDataTypeException
351
+	 * @throws InvalidInterfaceException
352
+	 * @throws InvalidEntityException
353
+	 * @throws DuplicateCollectionIdentifierException
354
+	 */
355
+	public function saveNotices()
356
+	{
357
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
358
+		if ($this->notice_collection->hasObjects()) {
359
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
360
+			// maybe initialize persistent_admin_notices
361
+			if (empty($persistent_admin_notices)) {
362
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
363
+			}
364
+			foreach ($this->notice_collection as $persistent_admin_notice) {
365
+				// are we deleting this notice ?
366
+				if ($persistent_admin_notice->getPurge()) {
367
+					unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
368
+				} else {
369
+					/** @var PersistentAdminNotice $persistent_admin_notice */
370
+					$persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
371
+						'message'     => $persistent_admin_notice->getMessage(),
372
+						'capability'  => $persistent_admin_notice->getCapability(),
373
+						'cap_context' => $persistent_admin_notice->getCapContext(),
374
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
375
+					);
376
+				}
377
+			}
378
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
379
+		}
380
+	}
381
+
382
+
383
+	/**
384
+	 * @throws DomainException
385
+	 * @throws InvalidDataTypeException
386
+	 * @throws InvalidEntityException
387
+	 * @throws InvalidInterfaceException
388
+	 * @throws DuplicateCollectionIdentifierException
389
+	 */
390
+	public function registerAndSaveNotices()
391
+	{
392
+		$this->getPersistentAdminNoticeCollection();
393
+		$this->registerNotices();
394
+		$this->saveNotices();
395
+		add_filter(
396
+			'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
397
+			'__return_true'
398
+		);
399
+	}
400
+
401
+
402
+	/**
403
+	 * @throws DomainException
404
+	 * @throws InvalidDataTypeException
405
+	 * @throws InvalidEntityException
406
+	 * @throws InvalidInterfaceException
407
+	 * @throws InvalidArgumentException
408
+	 * @throws DuplicateCollectionIdentifierException
409
+	 */
410
+	public static function loadRegisterAndSaveNotices()
411
+	{
412
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
413
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
414
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
415
+		);
416
+		// if shutdown has already run, then call registerAndSaveNotices() manually
417
+		if (did_action('shutdown')) {
418
+			$persistent_admin_notice_manager->registerAndSaveNotices();
419
+		}
420
+	}
421 421
 }
Please login to merge, or discard this patch.