Completed
Pull Request — 2.x (#4370)
by
unknown
05:02
created

PodsI18n::get_current_language_data()   F

Complexity

Conditions 53
Paths 1801

Size

Total Lines 223
Code Lines 76

Duplication

Lines 14
Ratio 6.28 %

Importance

Changes 0
Metric Value
cc 53
eloc 76
nc 1801
nop 1
dl 14
loc 223
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @package Pods
4
 * @since   2.7
5
 */
6
final class PodsI18n {
7
8
	/**
9
	 * @var PodsI18n Singleton instance
10
	 */
11
	private static $instance = null;
12
13
	/**
14
	 * @var array Key/value pairs with label/translation
15
	 */
16
	private static $strings = array();
17
18
	/**
19
	 * @var mixed Current language locale
20
	 */
21
	private static $current_language = null;
22
23
	/**
24
	 * @var mixed Current language data
25
	 */
26
	private static $current_language_data = null;
27
28
	/**
29
	 * Singleton handling for a basic pods_i18n() request
30
	 *
31
	 * @since 2.7
32
	 */
33
	private function __construct() {
34
		self::$instance = $this;
35
36
		// Hook all enqueue scripts actions
37
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
38
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
39
		add_action( 'login_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
40
	}
41
42
	/**
43
	 * Singleton handling for a basic pods_i18n() request
44
	 *
45
	 * @return \PodsI18n
46
	 *
47
	 * @since 2.7
48
	 */
49
	public static function get_instance() {
50
51
		// Initialize if the class hasn't been setup yet for some reason
52
		if ( ! is_object( self::$instance ) ) {
53
			self::$instance = new self();
54
		}
55
56
		return self::$instance;
57
	}
58
59
	/**
60
	 * @since 2.7
61
	 */
62
	public function enqueue_scripts() {
63
64
		// Register our i18n script for JS
65
		wp_register_script( 'sprintf', PODS_URL. 'ui/js/sprintf/sprintf.min.js', array(), '1.1.0', true );
66
		wp_register_script( 'pods-i18n', PODS_URL . 'ui/js/pods-i18n.js', array( 'sprintf' ), PODS_VERSION, true );
67
68
		self::localize_assets();
69
	}
70
71
	/**
72
	 * Localize assets:
73
	 *     * Build localizations strings from the defaults and those provided via filter
74
	 *     * Provide a global JavaScript object with the assembled localization strings via `wp_localize_script`
75
	 *
76
	 * @since 2.7
77
	 */
78
	private static function localize_assets() {
79
80
		/**
81
		 * Add strings to the localization
82
		 * Setting the key of your string to the original (non translated) value is mandatory
83
		 * Note: Existing keys in this class will overwrite the ones of this filter!
84
		 *
85
		 * @since 2.7
86
		 * @see   default_strings()
87
		 *
88
		 * @param array
89
		 *
90
		 * @return array format: 'Untranslated string' => 'Translated string with use of WP translate functions'
91
		 */
92
		$strings_extra = apply_filters( 'pods_localized_strings', array() );
93
94
		self::$strings = array_merge( $strings_extra, self::default_strings() );
95
96
		foreach ( self::$strings as $key => $str ) {
97
			self::register( $key, $str );
98
		}
99
100
		// Some other stuff we need to pass through
101
		$i18n_base = array(
102
			'debug' => ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG == true ) ? true : false,
103
		);
104
		// Add localization to our i18n script
105
		wp_localize_script( 'pods-i18n', 'podsLocalizedStrings', array_merge( self::$strings, $i18n_base ) );
106
	}
107
108
	/**
109
	 * Register function that creates the references and combines these with the translated strings
110
	 *
111
	 * @param string $string_key
112
	 * @param string $translation
113
	 *
114
	 * @since 2.7
115
	 */
116
	private static function register( $string_key, $translation ) {
117
118
		/**
119
		 * Converts string into reference object variable
120
		 * Uses the same logic as JS to create the same references
121
		 */
122
		$ref = '__' . $string_key;
123
124
		// Add it to the strings localized
125
		self::$strings[ $ref ] = $translation;
126
127
		// Remove the old key
128
		unset( self::$strings[ $string_key ] );
129
	}
130
131
	/**
132
	 * Register our labels to use in JS
133
	 * We need to register them as normal string to convert to JS references
134
	 * And we need to register the translations to attach to these references, these may not be variables!
135
	 *
136
	 * @return array Key/value pairs with label/translation
137
	 *
138
	 * @since 2.7
139
	 */
140
	private static function default_strings() {
141
142
		return array(
143
144
			'%s is required.' =>
145
				__( '%s is required.', 'pods' ),
146
147
			'This field is required.' =>
148
				__( 'This field is required.', 'pods' ),
149
150
			'Add' =>
151
				__( 'Add', 'pods' ),
152
153
			'Add New' =>
154
				__( 'Add New', 'pods' ),
155
156
			'Add New Record' =>
157
				__( 'Add New Record', 'pods' ),
158
159
			'Added!' =>
160
				__( 'Added!', 'pods' ),
161
162
			'Added! Choose another or <a href="#">close this box</a>' =>
163
				__( 'Added! Choose another or <a href="#">close this box</a>', 'pods' ),
164
165
			'Copy' =>
166
				__( 'Copy', 'pods' ),
167
168
			'Reorder' =>
169
				__( 'Reorder', 'pods' ),
170
171
			'Remove' =>
172
				__( 'Remove', 'pods' ),
173
174
			'Deselect' =>
175
				__( 'Deselect', 'pods' ),
176
177
			'Download' =>
178
				__( 'Download', 'pods' ),
179
180
			'View' =>
181
				__( 'View', 'pods' ),
182
183
			'Edit' =>
184
				__( 'Edit', 'pods' ),
185
186
			'Search' =>
187
				__( 'Search', 'pods' ),
188
189
			'Navigating away from this page will discard any changes you have made.' =>
190
				__( 'Navigating away from this page will discard any changes you have made.', 'pods' ),
191
192
			'Some fields have changes that were not saved yet, please save them or cancel the changes before saving the Pod.' =>
193
				__( 'Some fields have changes that were not saved yet, please save them or cancel the changes before saving the Pod.', 'pods' ),
194
195
			'Unable to process request, please try again.' =>
196
				__( 'Unable to process request, please try again.', 'pods' ),
197
198
			'Error uploading file: ' =>
199
				__( 'Error uploading file: ', 'pods' ),
200
201
			'Allowed Files' =>
202
				__( 'Allowed Files', 'pods' ),
203
204
			'The Title' =>
205
				__( 'The Title', 'pods' ),
206
207
			'Select from existing' =>
208
				__( 'Select from existing', 'pods' ),
209
210
			'You can only select' =>
211
				__( 'You can only select', 'pods' ),
212
213
			'%s item' =>
214
				__( '%s item', 'pods' ),
215
216
			'%s items' =>
217
				__( '%s items', 'pods' ),
218
219
			'Icon' =>
220
				__( 'Icon', 'pods' ),
221
222
		);
223
224
	}
225
226
	/**
227
	 * Get current locale information from Multilingual plugins
228
	 *
229
	 * @since 2.7
230
	 *
231
	 * @param array $args (optional) {
232
	 *     @type bool $refresh Rerun get_current_language() logic?
233
	 * }
234
	 *
235
	 * @return string
236
	 */
237
	public function get_current_language( $args = array() ) {
238
239
		$args = wp_parse_args( $args, array(
240
			'refresh' => false,
241
		) );
242
243
		if ( ! $args['refresh'] && ! empty( self::$current_language ) ) {
244
			return self::$current_language;
245
		}
246
247
		$this->get_current_language_data( $args );
248
		return self::$current_language;
249
	}
250
251
	/**
252
	 * Get current language information from Multilingual plugins
253
	 *
254
	 * @since 2.6.6
255
	 * @since 2.7 Moved to this class from PodsAPI
256
	 *
257
	 * @param array $args (optional) {
258
	 *     @type bool $refresh Rerun logic?
259
	 * }
260
	 *
261
	 * @return array
262
	 */
263
	public function get_current_language_data( $args = array() ) {
264
265
		$args = wp_parse_args( $args, array(
266
			'refresh' => false,
267
		) );
268
269
		if ( ! $args['refresh'] && ! empty( self::$current_language_data ) ) {
270
			return self::$current_language_data;
271
		}
272
273
		/**
274
		 * @var $sitepress SitePress object
275
		 * @var $polylang  Polylang object
276
		 */
277
		/*
278
		 * @todo wpml-comp Remove global object usage
279
		 */
280
		global $sitepress, $polylang;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
281
282
		$lang_data        = false;
283
		$translator       = false;
284
		$current_language = false;
285
286
		// Multilingual support
287
		if ( did_action( 'wpml_loaded' ) && apply_filters( 'wpml_setting', true, 'auto_adjust_ids' ) ) {
288
			// WPML support
289
			$translator = 'WPML';
290
291
			// Get the global current language (if set)
292
			$wpml_language = apply_filters( 'wpml_current_language', null );
293
			$current_language = ( $wpml_language != 'all' ) ? $wpml_language : '';
294
295
		} elseif ( ( function_exists( 'PLL' ) || is_object( $polylang ) ) && function_exists( 'pll_current_language' ) ) {
296
			// Polylang support
297
			$translator = 'PLL';
298
299
			// Get the global current language (if set)
300
			$current_language = pll_current_language( 'slug' );
301
		}
302
303
		/**
304
		 * Admin functions that overwrite the current language
305
		 *
306
		 * @since 2.6.6
307
		 */
308
		if ( is_admin() && ! empty( $translator ) ) {
309
			if ( $translator == 'PLL' ) {
310
				/**
311
				 * Polylang support
312
				 * Get the current user's preferred language.
313
				 * This is a user meta setting that will overwrite the language returned from pll_current_language()
314
				 * @see polylang/admin/admin-base.php -> init_user()
315
				 */
316
				$current_language = get_user_meta( get_current_user_id(), 'pll_filter_content', true );
317
			}
318
319
			// Get current language based on the object language if available
320
			if ( function_exists( 'get_current_screen' ) ) {
321
				$current_screen = get_current_screen();
322
323
				/**
324
				 * Overwrite the current language if needed for post types
325
				 */
326
				if ( isset( $current_screen->base ) && ( $current_screen->base == 'post' || $current_screen->base == 'edit' ) ) {
327
					if ( ! empty( $_GET['post'] ) ) {
328
						/**
329
						 * WPML support
330
						 * In WPML the current language is always set to default on an edit screen
331
						 * We need to overwrite this when the current object is not-translatable to enable relationships with different languages
332
						 */
333
						if (   $translator == 'WPML'
334
						       && ! apply_filters( 'wpml_is_translated_post_type', false, ( get_post_type( $_GET['post'] ) ) )
335
						) {
336
							// Overwrite the current language to nothing if this is a NOT-translatable post_type
337
							$current_language = '';
338
						}
339
340
						/**
341
						 * Polylang support (1.5.4+)
342
						 * In polylang the preferred language could be anything.
343
						 * We only want the related objects if they are not translatable OR the same language as the current object
344
						 */
345
						if (   $translator == 'PLL'
346
						       && function_exists( 'pll_get_post_language' )
347
						       && pll_is_translated_post_type( get_post_type( $_GET['post'] ) )
348
						) {
349
							// Overwrite the current language if this is a translatable post_type
350
							$current_language = pll_get_post_language( (int) $_GET['post'] );
351
						}
352
					}
353
354
					/**
355
					 * Polylang support (1.0.1+)
356
					 * In polylang the preferred language could be anything.
357
					 * When we're adding a new object and language is set we only want the related objects if they are not translatable OR the same language
358
					 */
359 View Code Duplication
					if (   $translator == 'PLL'
360
					       && ! empty( $_GET['new_lang'] )
361
					       && ! empty( $_GET['post_type'] )
362
					       && pll_is_translated_post_type( sanitize_text_field( $_GET['post_type'] ) )
363
					) {
364
						$current_language = $_GET['new_lang'];
365
					}
366
367
					/**
368
					 * Overwrite the current language if needed for taxonomies
369
					 */
370
				} elseif ( isset( $current_screen->base ) && ( $current_screen->base == 'term' || $current_screen->base == 'edit-tags' ) ) {
371
					// @todo MAYBE: Similar function like get_post_type for taxonomies so we don't need to check for $_GET['taxonomy']
372
					if ( ! empty( $_GET['taxonomy'] ) ) {
373
						/*
374
						 * @todo wpml-comp API call for taxonomy needed!
375
						 * Suggested API call:
376
						 * add_filter( 'wpml_is_translated_taxonomy', $_GET['taxonomy'], 10, 2 );
377
						 */
378
						/**
379
						 * WPML support
380
						 * In WPML the current language is always set to default on an edit screen
381
						 * We need to overwrite this when the current object is not-translatable to enable relationships with different languages
382
						 */
383
						if (   $translator == 'WPML'
384
						       && method_exists( $sitepress, 'is_translated_taxonomy')
385
						       && ! $sitepress->is_translated_taxonomy( $_GET['taxonomy'] )
386
						) {
387
							// Overwrite the current language to nothing if this is a NOT-translatable taxonomy
388
							$current_language = '';
389
						}
390
391
						/**
392
						 * Polylang support (1.5.4+)
393
						 * In polylang the preferred language could be anything.
394
						 * We only want the related objects if they are not translatable OR the same language as the current object
395
						 */
396
						if (   $translator == 'PLL'
397
						       && ! empty( $_GET['tag_ID'] )
398
						       && function_exists( 'pll_get_term_language' )
399
						       && pll_is_translated_taxonomy( sanitize_text_field( $_GET['taxonomy'] ) )
400
						) {
401
							// Overwrite the current language if this is a translatable taxonomy
402
							$current_language = pll_get_term_language( (int) $_GET['tag_ID'] );
403
						}
404
					}
405
406
					/**
407
					 * Polylang support (1.0.1+)
408
					 * In polylang the preferred language could be anything.
409
					 * When we're adding a new object and language is set we only want the related objects if they are not translatable OR the same language
410
					 */
411 View Code Duplication
					if (   $translator == 'PLL'
412
					       && ! empty( $_GET['new_lang'] )
413
					       && ! empty( $_GET['taxonomy'] )
414
					       && pll_is_translated_taxonomy( sanitize_text_field( $_GET['taxonomy'] ) )
415
					) {
416
						$current_language = $_GET['new_lang'];
417
					}
418
				}
419
			}
420
		}
421
422
		$current_language = pods_sanitize( sanitize_text_field( $current_language ) );
423
424
		if ( ! empty( $current_language ) ) {
425
			// We need to return language data
426
			$lang_data = array(
427
				'language' => $current_language,
428
				't_id'     => 0,
429
				'tt_id'    => 0,
430
				'term'     => null,
431
			);
432
433
			/**
434
			 * Polylang support
435
			 * Get the language taxonomy object for the current language
436
			 */
437
			if ( $translator == 'PLL' ) {
438
				$current_language_t = false;
439
440
				// Get the language term object
441
				if ( function_exists( 'PLL' ) && isset( PLL()->model ) && method_exists( PLL()->model, 'get_language' ) ) {
442
					// Polylang 1.8 and newer
443
					$current_language_t = PLL()->model->get_language( $current_language );
444
				} elseif ( is_object( $polylang ) && isset( $polylang->model ) && method_exists( $polylang->model, 'get_language' ) ) {
445
					// Polylang 1.2 - 1.7.x
446
					$current_language_t = $polylang->model->get_language( $current_language );
447
				} elseif ( is_object( $polylang ) && method_exists( $polylang, 'get_language' ) ) {
448
					// Polylang 1.1.x and older
449
					$current_language_t = $polylang->get_language( $current_language );
450
				}
451
452
				// If the language object exists, add it!
453
				if ( $current_language_t && ! empty( $current_language_t->term_id ) ) {
454
					$lang_data['t_id']  = (int) $current_language_t->term_id;
455
					$lang_data['tt_id'] = (int) $current_language_t->term_taxonomy_id;
456
					$lang_data['tl_t_id'] = (int) $current_language_t->tl_term_id;
457
					$lang_data['tl_tt_id'] = (int) $current_language_t->tl_term_taxonomy_id;
458
					$lang_data['term']  = $current_language_t;
459
				}
460
			}
461
		}
462
463
		/**
464
		 * Override language data used by Pods.
465
		 *
466
		 * @since 2.6.6
467
		 *
468
		 * @param array|false    $lang_data {
469
		 *      Language data
470
		 *
471
		 *      @type string       $language  Language slug
472
		 *      @type int          $t_id      Language term_id
473
		 *      @type int          $tt_id     Language term_taxonomy_id
474
		 *      @type WP_Term      $term      Language term object
475
		 * }
476
		 * @param string|boolean $translator Language plugin used
477
		 */
478
		$lang_data = apply_filters( 'pods_get_current_language', $lang_data, $translator );
479
480
		self::$current_language = $lang_data['language'];
481
		self::$current_language_data = $lang_data;
482
483
		return $lang_data;
484
485
	}
486
487
}
488