Completed
Push — master ( eef885...465d0c )
by
unknown
30:08 queued 12:49
created

JSON_Util   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 77
Duplicated Lines 20.78 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 16
loc 77
rs 10
c 0
b 0
f 0
wmc 14
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A construct() 0 1 1
D open_and_decode() 16 37 9
A decode() 0 18 4

How to fix   Duplicated Code   

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:

1
<?php
2
/**
3
 * Gestion des fichiers JSON
4
 *
5
 * @package Evarisk\Plugin
6
 */
7
8
namespace eoxia;
9
10
if ( ! defined( 'ABSPATH' ) ) {
11
	exit;
12
}
13
14
if ( ! class_exists( '\eoxia\JSON_Util' ) ) {
15
	/**
16
	 * Gestion des fichiers JSON
17
	 *
18
	 * @author Jimmy Latour <[email protected]>
19
	 * @version 1.1.0.0
20
	 */
21
	class JSON_Util extends \eoxia\Singleton_Util {
22
		/**
23
		 * Le constructeur obligatoirement pour utiliser la classe \eoxia\Singleton_Util
24
		 *
25
		 * @return void nothing
26
		 */
27
		protected function construct() {}
28
29
			/**
30
		 * Ouvres et décode le fichier JSON $path_to_json
31
		 *
32
		 * @param  string $path_to_json Le chemin vers le fichier JSON.
33
		 * @return array              	Les données du fichier JSON
34
		 */
35
		public function open_and_decode( $path_to_json, $output = 'STDCLASS' ) {
36 View Code Duplication
			if ( ! file_exists( $path_to_json ) ) {
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...
37
				if ( function_exists( 'eo_log' ) ) {
38
					eo_log( 'digi_open_and_decode', array(
39
						'message' => 'Impossible d\'ouvrir le fichier json: ' . $path_to_json,
40
					), 2 );
41
				} else {
42
					return new \WP_Error( 'broke', __( 'Impossible d\'ouvrir le fichier JSON', 'digirisk' ) );
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \WP_Error('br...er JSON', 'digirisk')); (WP_Error) is incompatible with the return type documented by eoxia\JSON_Util::open_and_decode of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
43
				}
44
			}
45
46
			$config_content = file_get_contents( $path_to_json );
47
48
			if ( 'STDCLASS' === $output ) {
49
				$data = json_decode( $config_content );
50
			} elseif ( 'ARRAY_A' === $output ) {
51
				$data = json_decode( $config_content, true );
52
			}
53
54
			if ( null === $data && json_last_error() !== JSON_ERROR_NONE ) {
0 ignored issues
show
Bug introduced by
The variable $data 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...
55 View Code Duplication
				if ( function_exists( 'eo_log' ) ) {
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...
56
					eo_log( 'digi_open_and_decode', array(
57
						'message' => 'Les données dans le fichier json: ' . $path_to_json . ' semble erronées',
58
					), 2 );
59
				} else {
60
					return new \WP_Error( 'broke', __( 'Les données du fichier JSON semble erronnés', 'digirisk' ) );
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \WP_Error('br...ronnés', 'digirisk')); (WP_Error) is incompatible with the return type documented by eoxia\JSON_Util::open_and_decode of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
61
				}
62
			}
63
64
			if ( function_exists( 'eo_log' ) ) {
65
				eo_log( 'digi_open_and_decode', array(
66
					'message' => 'Le fichier json: ' . $path_to_json . ' sont : ' . wp_json_encode( $data ),
67
				), 2 );
68
			}
69
70
			return $data;
71
		}
72
73
		/**
74
		 * Décodes la chaine de caractère $json_to_decode
75
		 *
76
		 * @param  string $json_to_decode La chaine de caractère JSON.
77
		 * @return array              		Les données décodées
78
		 */
79
		public function decode( $json_to_decode ) {
80
			if ( ! is_string( $json_to_decode ) ) {
81
				return $json_to_decode;
82
			}
83
84
			$json_decoded = json_decode( $json_to_decode, true );
85
86
			if ( ! $json_decoded ) {
87
				$json_to_decode = str_replace( '\\', '', $json_to_decode );
88
				$json_decoded = json_decode( $json_to_decode, true );
89
90
				if ( ! $json_decoded ) {
91
					return $json_to_decode;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $json_to_decode; (string) is incompatible with the return type documented by eoxia\JSON_Util::decode of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
92
				}
93
			}
94
95
			return $json_decoded;
96
		}
97
	}
98
} // End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
99