ImportJSONData   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 170
rs 10
c 0
b 0
f 0
wmc 27
lcom 1
cbo 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A addDefaultParams() 0 11 1
F execute() 0 95 15
A csv_to_array() 0 11 2
A arraySort() 0 7 2
A removeKeys() 0 12 3
A isJSON() 0 3 3
1
<?php
2
3
$basePath = getenv( 'MW_INSTALL_PATH' ) !== false ? getenv( 'MW_INSTALL_PATH' ) : __DIR__ . '/../../..';
4
require_once $basePath . '/maintenance/Maintenance.php';
5
6
7
class ImportJSONData extends Maintenance {
8
9
10
	public function __construct() {
11
		parent::__construct();
12
		$this->addDescription( "\n" .
13
			"Script for importing data stored in JSON stores\n"
14
		);
15
		$this->addDefaultParams();
16
	}
17
18
    /**
19
	 * @see Maintenance::addDefaultParams
20
	 */
21
	protected function addDefaultParams() {
22
		$this->addOption( 'delimiter', 'The delimiter parameter sets the field delimiter (a single character)', false, true, "d" );
23
		$this->addOption( 'separator', 'The separator parameter sets the surrounding character of each field (a single character)', false, true, "s" );
24
		$this->addOption( 'namespace', 'Namespace where to store data (main namespace, empty one, by default)', false, true, "n" );
25
		$this->addOption( 'rowfields', 'Comma-separated list of fields to consider', false, true, "f" );
26
		$this->addOption( 'rowobject', 'Subobject row property', false, true, "r" );
27
        $this->addOption( 'user', 'Username to which edits should be attributed. ' .'Default: "Maintenance script"', false, true, 'u' );
28
        $this->addOption( 'single', 'Enable single mode import', false, false, 'i' );
29
        $this->addOption( 'overwrite', 'Whether to overwrite existing content', false, false, 'w' );        
30
        // $this->addArg( 'file', 'Data files to be imported' );
31
    }
32
33
    /**
34
	 * @see Maintenance::execute
35
	 */
36
	public function execute() {
37
    
38
        $delimiter = $this->getOption( "delimiter", '"' );
39
        $separator = $this->getOption( "separator", ',' );
40
        $namespace = $this->getOption( "namespace", '' ); 
41
        $rowobject = $this->getOption( "rowobject", null ); 
42
        $rowfields = $this->getOption( "rowfields", null );
43
        $userName = $this->getOption( 'user', false );
44
        $single = $this->getOption( 'single', false );
45
        $overwrite = $this->getOption( 'overwrite', true );
46
47
        // Get all the arguments. A loop is required since Maintenance doesn't
48
        // suppport an arbitrary number of arguments.
49
        $files = [];
50
        $i = 0;
51
        while ( $arg = $this->getArg( $i++ ) ) {
52
                if ( file_exists( $arg ) ) {
53
                        $files[$arg] = file_get_contents( $arg );
54
                } else {
55
                        $this->error( "Fatal error: The file '$arg' does not exist!", 1 );
56
                }
57
        };
58
59
        $count = count( $files );
60
        $this->output( "Importing $count pages...\n" );
61
62
        if ( $userName === false ) {
63
                $user = User::newSystemUser( 'Maintenance script', [ 'steal' => true ] );
64
        } else {
65
                $user = User::newFromName( $userName );
66
        }
67
68
        if ( !$user ) {
69
                $this->error( "Invalid username\n", true );
70
        }
71
        if ( $user->isAnon() ) {
72
                $user->addToDatabase();
73
        }
74
75
        // TODO: Need to review this in a more efficient way
76
        foreach ( $files as $file => $text ) {
77
78
            if( $this->isJSON($rowfields) ){
79
                  $row=json_decode($rowfields);
80
                  $rowfields="";
0 ignored issues
show
Unused Code introduced by
$rowfields 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...
81
                  $rowfields=$row;
82
            }
83
            
84
            $data = $this->csv_to_array( $text, trim( $separator ), trim( $delimiter ) );
85
            
86
            $dataObj = $this->arraySort( $data );
87
            
88
            for( $i=0; $i<count($dataObj); $i++ ){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
89
                
90
                $title = "";
91
                
92
                for( $j=0; $j<count($dataObj[$i]); $j++ ){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
93
                    $title = array_shift( $dataObj[$i][$j] );
94
                }
95
                //print_r($dataObj[$i]);
96
                
97
                $metaObj = array( 'app' => 'SDI','version' => 0.1 );
98
                
99
                if ( $rowobject ) {
100
                    $metaObj["rowobject"] = $rowobject;
101
                }
102
                
103
                if ( $rowfields ) {
104
                    $metaObj["rowfields"] = $rowfields;          
105
                }
106
                
107
                if ( $single ) {
108
                    $metaObj["single"] = true;
109
                }
110
                
111
                $obj = array('data' => $dataObj[$i],'meta' => $metaObj );
112
    
113
                //print_r($obj);
114
                $jsonStr = json_encode( $obj );
115
                //print_r($jsonStr);
116
                if ( ! empty( $title ) ) {
117
                    
118
                    $fulltitle = $title;
119
                    if ( $namespace !== "" ) {
120
                        $fulltitle = $namespace.":".$title;
121
                    }
122
                    
123
                    $status = SDImportData::importJSON( $jsonStr, $fulltitle, $overwrite );
0 ignored issues
show
Unused Code introduced by
$status 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...
124
                    echo "Data ".$fulltitle." completed\n";
125
                }
126
            }
127
            echo "\nHas been successfully completed\n";
128
        }
129
    
130
    }
131
132
    /**
133
        This function parse the array with a delimiter and a separator given by the user
134
    **/
135
    private function csv_to_array( $text, $delimiter, $separator ){
136
        
137
        // Splitting lines
138
        $lines = preg_split( '/$\R?^/m', $text );
139
        
140
        foreach ( $lines as $line ) {
141
            $data[] = str_getcsv( $text, $delimiter, $separator );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
142
        }
143
144
        return $data;
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...
145
    }
146
    /**
147
        Sort the array and group it by title
148
    **/
149
    private function arraySort($input){
150
        
151
        foreach ($input as $key=>$val) $output[$val[0]][]=$val;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$output was never initialized. Although not strictly required by PHP, it is generally a good practice to add $output = 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...
152
        $output = $this->removeKeys( $output );
0 ignored issues
show
Bug introduced by
The variable $output 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...
153
        return $output;
154
    
155
    }
156
    /**
157
        Remove the keys from the array
158
    **/
159
    private function removeKeys( array $array ){
160
        
161
        $array = array_values( $array );
162
        foreach ( $array as &$value ){
163
            if ( is_array( $value ) ){
164
                $value = removeKeys( $value );
165
            }
166
        }
167
        
168
        return $array;
169
    
170
    }
171
172
    private function isJSON($string){
173
        return is_string($string) && is_array(json_decode($string, true)) ? true : false;
174
    }
175
176
}
177
178
179
$maintClass = 'ImportJSONData';
180
require_once( DO_MAINTENANCE );
181
182