Completed
Push — master ( b29ded...4ab3b6 )
by
unknown
01:59
created

lasso   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 501
Duplicated Lines 13.77 %

Coupling/Cohesion

Components 4
Dependencies 1

Importance

Changes 0
Metric Value
dl 69
loc 501
rs 3.2
c 0
b 0
f 0
wmc 65
lcom 4
cbo 1

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 31 1
A get_plugin_slug() 0 3 1
A get_instance() 0 9 2
A activate() 26 26 5
A deactivate() 27 27 5
A activate_new_site() 0 11 2
A get_blog_ids() 0 12 1
A single_activate() 0 17 2
A single_deactivate() 0 3 1
A load_plugin_textdomain() 0 7 1
A editus_lock_post() 0 14 2
A editus_hide_tour() 0 7 1
B editus_set_post_setting() 0 47 9
A enable_metasave() 0 14 2
A editus_do_shortcode() 0 24 2
C get_aesop_component() 0 66 15
A get_ase_options() 0 7 1
B set_post_terms() 0 32 7
A getEnglishMonthName() 4 16 3
A set_date() 12 12 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like lasso often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use lasso, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * AH Editor
4
 *
5
 * @package   Lasso
6
 * @author    Nick Haskins <[email protected]>
7
 * @license   GPL-2.0+
8
 * @link      http://aesopinteractive.com
9
 * @copyright 2015-2017 Aesopinteractive 
10
 */
11
namespace lasso_public_facing;
12
/**
13
 *
14
 *
15
 * @package Lasso
16
 * @author  Nick Haskins <[email protected]>
17
 */
18
class lasso {
19
20
	/**
21
	 *
22
	 *
23
	 * @since    0.0.1
24
	 *
25
	 * @var      string
26
	 */
27
	protected $plugin_slug = 'lasso';
28
29
	/**
30
	 * Instance of this class.
31
	 *
32
	 * @since    0.0.1
33
	 *
34
	 * @var      object
35
	 */
36
	protected static $instance = null;
37
38
	/**
39
	 *
40
	 *
41
	 * @since     0.0.1
42
	 */
43
	private function __construct() {
44
45
		require_once LASSO_DIR.'/public/includes/underscore-templates.php';
46
47
		require_once LASSO_DIR.'/public/includes/editor-modules.php';
48
		require_once LASSO_DIR.'/public/includes/helpers.php';
49
		require_once LASSO_DIR.'/public/includes/editor-modules--gallery.php';
50
		require_once LASSO_DIR.'/public/includes/components.php';
51
		require_once LASSO_DIR.'/public/includes/option-engine.php';
52
		require_once LASSO_DIR.'/public/includes/wrap-shortcodes.php';
53
54
		// Activate plugin when new blog is added
55
		add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );
56
57
		// Load plugin text domain
58
		add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
59
		
60
		add_action( 'wp_ajax_get_aesop_component',     array( $this, 'get_aesop_component' ) );
61
		add_action( 'wp_ajax_editus_do_shortcode',     array( $this, 'editus_do_shortcode' ) );
62
		add_action( 'wp_ajax_editus_lock_post',     array( $this, 'editus_lock_post' ) );
63
		add_action( 'wp_ajax_editus_hide_tour',     array( $this, 'editus_hide_tour' ) );
64
		add_action( 'wp_ajax_editus_set_post_setting',     array( $this, 'editus_set_post_setting' ) );
65
		add_action( 'wp_ajax_editus_get_ase_options',     array( $this, 'get_ase_options' ) );
66
67
		// enable saving custom fields through REST API
68
		self::enable_metasave('post');
69
		self::enable_metasave('page');
70
		//enqueue assets
71
		new assets();
72
73
	}
74
75
	/**
76
	 * Return the plugin slug.
77
	 *
78
	 * @since    0.0.1
79
	 *
80
	 * @return    Plugin slug variable.
81
	 */
82
	public function get_plugin_slug() {
83
		return $this->plugin_slug;
84
	}
85
86
	/**
87
	 * Return an instance of this class.
88
	 *
89
	 * @since     0.0.1
90
	 *
91
	 * @return    object    A single instance of this class.
92
	 */
93
	public static function get_instance() {
94
95
		// If the single instance hasn't been set, set it now.
96
		if ( null == self::$instance ) {
97
			self::$instance = new self;
98
		}
99
100
		return self::$instance;
101
	}
102
103
	/**
104
	 * Fired when the plugin is activated.
105
	 *
106
	 * @since    0.0.1
107
	 *
108
	 * @param boolean $network_wide True if WPMU superadmin uses
109
	 *                                       "Network Activate" action, false if
110
	 *                                       WPMU is disabled or plugin is
111
	 *                                       activated on an individual blog.
112
	 */
113 View Code Duplication
	public static function activate( $network_wide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
114
115
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
116
117
			if ( $network_wide  ) {
118
119
				// Get all blog ids
120
				$blog_ids = self::get_blog_ids();
121
122
				foreach ( $blog_ids as $blog_id ) {
0 ignored issues
show
Bug introduced by
The expression $blog_ids of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
123
124
					switch_to_blog( $blog_id );
125
					self::single_activate();
126
				}
127
128
				restore_current_blog();
129
130
			} else {
131
				self::single_activate();
132
			}
133
134
		} else {
135
			self::single_activate();
136
		}
137
138
	}
139
140
	/**
141
	 * Fired when the plugin is deactivated.
142
	 *
143
	 * @since    0.0.1
144
	 *
145
	 * @param boolean $network_wide True if WPMU superadmin uses
146
	 *                                       "Network Deactivate" action, false if
147
	 *                                       WPMU is disabled or plugin is
148
	 *                                       deactivated on an individual blog.
149
	 */
150 View Code Duplication
	public static function deactivate( $network_wide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
151
152
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
153
154
			if ( $network_wide ) {
155
156
				// Get all blog ids
157
				$blog_ids = self::get_blog_ids();
158
159
				foreach ( $blog_ids as $blog_id ) {
0 ignored issues
show
Bug introduced by
The expression $blog_ids of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
160
161
					switch_to_blog( $blog_id );
162
					self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
163
164
				}
165
166
				restore_current_blog();
167
168
			} else {
169
				self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
170
			}
171
172
		} else {
173
			self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
174
		}
175
176
	}
177
178
	/**
179
	 * Fired when a new site is activated with a WPMU environment.
180
	 *
181
	 * @since    0.0.1
182
	 *
183
	 * @param int     $blog_id ID of the new blog.
184
	 */
185
	public function activate_new_site( $blog_id ) {
186
187
		if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
188
			return;
189
		}
190
191
		switch_to_blog( $blog_id );
192
		self::single_activate();
193
		restore_current_blog();
194
195
	}
196
197
	/**
198
	 * Get all blog ids of blogs in the current network that are:
199
	 * - not archived
200
	 * - not spam
201
	 * - not deleted
202
	 *
203
	 * @since    0.0.1
204
	 *
205
	 * @return   array|false    The blog ids, false if no matches.
206
	 */
207
	private static function get_blog_ids() {
208
209
		global $wpdb;
210
211
		// get an array of blog ids
212
		$sql = "SELECT blog_id FROM $wpdb->blogs
213
			WHERE archived = '0' AND spam = '0'
214
			AND deleted = '0'";
215
216
		return $wpdb->get_col( $sql );
217
218
	}
219
220
	/**
221
	 * Fired for each blog when the plugin is activated.
222
	 *
223
	 * @since    0.0.1
224
	 */
225
	private static function single_activate() {
226
227
		$curr_version = get_option( 'lasso_version' );
228
229
		// update upgraded from
230
		if ( $curr_version ) {
231
			update_option( 'lasso_updated_from', $curr_version );
232
		}
233
234
		// update lasso version option
235
		update_option( 'lasso_version', LASSO_VERSION );
236
237
		// set transietn for activation welcome
238
		set_transient( '_lasso_welcome_redirect', true, 30 );
239
240
241
	}
242
243
	/**
244
	 * Fired for each blog when the plugin is deactivated.
245
	 *
246
	 * @since    0.0.1
247
	 */
248
	private static function single_deactivate() {
249
		// @TODO: Define deactivation functionality here
250
	}
251
252
	/**
253
	 * Load the plugin text domain for translation.
254
	 *
255
	 * @since    1.0.0
256
	 */
257
	public function load_plugin_textdomain() {
258
259
		$domain = $this->plugin_slug;
260
		$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
261
262
		$out = load_textdomain( $domain, trailingslashit( LASSO_DIR ). 'languages/' . $domain . '-' . $locale . '.mo' );
0 ignored issues
show
Unused Code introduced by
$out is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
263
	}
264
	
265
    // new ajax function to lock post for editing
266
	public function editus_lock_post()
267
	{
268
		$post_id= $_POST["postid"];
269
		$locked = wp_check_post_lock($post_id);
270
		
271
		if (!$locked) {
272
		    wp_set_post_lock($post_id);
273
			echo "true";
274
		} else {
275
			$user_info = get_userdata($locked);
276
			echo "Post opened by ".$user_info->first_name .  " " . $user_info->last_name;
277
		}
278
		exit;
279
	}
280
	
281
	// new ajax function to update tour setting
282
	public function editus_hide_tour()
283
	{
284
		$user_id = get_current_user_ID();
285
				
286
		update_user_meta( $user_id, 'lasso_hide_tour', true );
287
		exit;
288
	}
289
	
290
	public function editus_set_post_setting()
291
	{
292
		
293
		
294
		$data = array();
295
		parse_str($_POST['data'], $data);
296
		
297
		if (!wp_verify_nonce( $data[ 'nonce' ], 'lasso-update-post-settings' )) {
298
			wp_send_json_error();
299
			exit;
300
		}
301
		
302
		$status = isset( $data['status'] ) ? $data['status'] : false;
303
		$postid = isset( $data['postid'] ) ? $data['postid'] : false;
304
		$slug   = isset( $data['story_slug'] ) ? $data['story_slug'] : false;
305
	
306
307
		$args = array(
308
			'ID'   			=> (int) $postid,
309
			'post_name'  	=> $slug,
310
			'post_status' 	=> $status
311
		);
312
		
313
		
314
315
		wp_update_post( apply_filters( 'lasso_object_status_update_args', $args ) );
316
		
317
		// update categories
318
		$cats  = isset( $data['story_cats'] ) ? $data['story_cats'] : false;
319
		
320
		self::set_post_terms( $postid, $cats, 'category' );
321
		
322
		// update tags
323
		$tags = isset( $data['story_tags'] ) ? $data['story_tags'] : false;
324
		self::set_post_terms( $postid, $tags, 'post_tag' );
325
		
326
		//update date
327
		$date  = isset( $data['post_date'] ) ? $data['post_date'] : false;
328
		self::set_date( $postid, $date );
329
		
330
		do_action( 'lasso_post_updated', $postid, $slug, $status, get_current_user_ID() );
331
		$response= array(
332
			'link'   => get_permalink($postid). (($status=='publish') ? '' : '&preview=true')
333
		);
334
		wp_send_json_success($response);
335
		exit;
336
	}
337
	
338
	public static function enable_metasave($type)
339
	{
340
		register_rest_field( $type, 'metadata', array(
341
			'get_callback' => function ( $data ) {
342
				return get_post_meta( $data['id']);//, '', '' );
343
			}, 
344
			'update_callback' => function( $data, $post ) {
345
				foreach ($data as $key => $value) {
346
					update_post_meta($post->ID, $key, $value);
347
				}
348
				return true;
349
			}
350
		));
351
	}
352
	
353
	public function editus_do_shortcode()
354
	{
355
		
356
		$code= $_POST["code"];
357
		$code = str_replace('\"', '"', $code);
358
		
359
		$code_wrapped = lasso_wrap_shortcodes( $code);
360
		$out =  do_shortcode($code);
361
		if ($out != '') {
362
			$out =  do_shortcode($code_wrapped);
363
			echo $out;
364
			exit;
365
		}
366
		
367
		// do_shortcode didn't work. Try again using wp_embed
368
369
		/** @var \WP_Embed $wp_embed */
370
		global $wp_embed;
371
		$wp_embed->post_ID = $_POST["ID"];
372
		$out =$wp_embed->run_shortcode( $code_wrapped );
373
		
374
		echo $out;
375
		exit;
376
	}
377
	
378
	public function get_aesop_component()
379
	{
380
		
381
		
382
		$code= $_POST["code"];
383
		$atts = array(
384
		 );
385
		foreach ($_POST as $key => $value) {
386
			if ($key !="code" && $key !="action") {
387
			    //$shortcode = $shortcode.$key.'="'.$value.'" ';
388
				$atts[$key] = $value;
389
			}
390
		}
391
		if ($code == "aesop_video") {
392
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-video.php');
393
		    echo aesop_video_shortcode($atts);
394
		}
395
		else if ($code == "aesop_image") {
396
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-image.php');
397
		    echo aesop_image_shortcode($atts);
398
		}
399
		else if ($code == "aesop_quote") {
400
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-quote.php');
401
		    echo aesop_quote_shortcode($atts);
402
		}
403
		else if ($code == "aesop_parallax") {
404
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-parallax.php');
405
		    echo aesop_parallax_shortcode($atts);
406
		}
407
		else if ($code == "aesop_character") {
408
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-character.php');
409
		    echo aesop_character_shortcode($atts);
410
		}
411
		else if ($code == "aesop_collection") {
412
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-collections.php');
413
		    echo aesop_collection_shortcode($atts);
414
		}
415
		else if ($code == "aesop_chapter") {
416
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-heading.php');
417
		    echo aesop_chapter_shortcode($atts);
418
		}
419
		else if ($code == "aesop_content") {
420
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-cbox.php');
421
		    echo aesop_content_shortcode($atts, $atts['content_data']);
422
		}
423
		else if ($code == "aesop_gallery") {
424
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-gallery.php');
425
		    echo do_shortcode( '[aesop_gallery id="'.$atts["id"].'"]');
426
		}
427
		else if ($code == "aesop_audio") {
428
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-audio.php');
429
		    echo aesop_audio_shortcode($atts);
430
		}
431
		else {
432
			$code = '['.$code.' ';
433
			foreach ($atts as $key => $value) {
434
			    $code = ''.$key.'="'.$value.'" ';
435
			}
436
			$code = $code.']';
437
			echo do_shortcode($code);
438
		    //require_once( ABSPATH . '/wp-content/plugins/aesop-events/public/includes/shortcode.php');
439
		    //echo aesop_audio_shortcode($atts);
440
		}
441
		
442
		exit; 
443
	}
444
	
445
	
446
	public function get_ase_options()
447
	{
448
		$blob = lasso_editor_options_blob();
449
		$code= $_POST["component"];
450
		echo $blob[$code];
451
		exit; 
452
	}
453
	
454
	public function set_post_terms( $postid, $value, $taxonomy ) {
455
		if( $value ) {
456
			$value = explode( ',', $value );
457
			$allow_new_category = lasso_editor_get_option( 'allow_new_category', 'lasso_editor' );
458
			
459
			if ($taxonomy =='category') {
460
                // convert from names to category ids
461
				$cats = array();
462
				foreach ($value as $cat) {
463
					$cat_id = get_cat_ID($cat);
464
					if ($cat_id !=0) {
465
						$cats [] = $cat_id;
466
					} else if ($allow_new_category) {
467
					    $cats [] = wp_create_category($cat);
468
					}
469
				}
470
				$value = $cats;
471
			}
472
	
473
			$result = wp_set_object_terms( $postid, $value, $taxonomy );
474
		}
475
		else  {
476
			//remove all terms from post
477
			$result = wp_set_object_terms( $postid, null, $taxonomy );
478
		}
479
480
		if ( ! is_wp_error( $result ) ) {
481
			return true;
482
		}else{
483
			return false;
484
		}
485
	}
486
	
487
	function getEnglishMonthName($foreignMonthName){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
488
489
		  setlocale(LC_ALL, 'en_US');
490
491
		  $month_numbers = range(1,12);
492
493 View Code Duplication
		  foreach($month_numbers as $month)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
494
			$english_months[] = strftime('%B',mktime(0,0,0,$month,1,2011));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$english_months was never initialized. Although not strictly required by PHP, it is generally a good practice to add $english_months = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
495
496
		  setlocale(LC_ALL, get_locale());
497
498 View Code Duplication
		  foreach($month_numbers as $month)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
499
			$foreign_months[] = strftime('%B',mktime(0,0,0,$month,1,2011));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$foreign_months was never initialized. Although not strictly required by PHP, it is generally a good practice to add $foreign_months = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
500
501
		  return str_replace($foreign_months, $english_months, $foreignMonthName);
0 ignored issues
show
Bug introduced by
The variable $foreign_months does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $english_months does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
502
	}
503
504
505
	
506 View Code Duplication
	public function set_date( $postid, $value) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
507
		if( $value ) {
508
			$value = self::getEnglishMonthName($value);
509
            wp_update_post(
510
				array (
511
					'ID'            => $postid, // ID of the post to update
512
					'post_date'     => date( 'Y-m-d H:i:s',  strtotime($value) ),
513
					'post_date_gmt'     => gmdate( 'Y-m-d H:i:s',  strtotime($value) ),
514
				)
515
			);
516
		}
517
	}
518
}
519