Completed
Push — master ( e8d4d8...52de20 )
by Toni Hermoso
16:34
created

SDImportDataParser   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 231
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 231
rs 9.52
c 0
b 0
f 0
wmc 36
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
F processData() 0 112 19
F prepareLink() 0 76 13
A getCSVData() 0 19 4
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 9 and the first side effect is on line 4.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
if ( !defined( 'MEDIAWIKI' ) ) {
4
	echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
5
}
6
7
/** In this class we store things related to data processing **/
8
9
class SDImportDataParser {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
11
	/**
12
	* @param $input string
13
	* @param $args array
14
	* @param $parser Parser
15
	* @param $frame Frame
16
	* @return string
17
	*/
18
	public static function processData( $input, $args, $parser, $frame ) {
0 ignored issues
show
Unused Code introduced by
The parameter $frame is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
19
	
20
		global $wgSDImportDataPage;
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...
21
		$pageTitle = $parser->getTitle();
22
		$output = "";
23
24
		$separator="\t";
25
		$delimiter='"';
26
		$fields = array();
27
28
		if ( is_object( $pageTitle ) ) {
29
30
			$ns = $pageTitle->getNsText();
31
			
32
			# Handle main namespace with _
33
			if ( $ns == "" ) {
34
				$ns = "_";
35
			}
36
37
			if ( key_exists( $ns, $wgSDImportDataPage ) ) {
38
39
				$nsRepo = $wgSDImportDataPage[$ns];
40
				
41
				$separator = SDImportData::getSelector( $args, $nsRepo, "separator" ); // String
42
				$delimiter = SDImportData::getSelector( $args, $nsRepo, "delimiter" ); // String
43
				$object = SDImportData::getSelector( $args, $nsRepo, "rowobject" ); // String
44
				$fields = SDImportData::getSelector( $args, $nsRepo, "rowfields" ); // Array
45
				$props = SDImportData::getSelector( $args, $nsRepo, "typefields" ); // Array
0 ignored issues
show
Unused Code introduced by
$props 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...
46
				$refs = SDImportData::getSelector( $args, $nsRepo, "ref" ); // Hash
47
				$pre = SDImportData::getSelector( $args, $nsRepo, "prefields" ); // Array
48
				$post = SDImportData::getSelector( $args, $nsRepo, "postfields" ); // Array
49
				$editable = SDImportData::getSelector( $args, $nsRepo, "edit" ); // Boolean
50
				// TODO: Add single option here maybe?
51
52
				// TODO: Should we add props here if they don't exist?
53
				
54
55
				$dprops = array();
56
57
				if ( $refs ) {
58
					foreach ( $refs as $key => $val ) {
59
						$dprops[ $key ] = SDImportData::processWikiText( $val, $pageTitle );
60
					}
61
				}
62
				
63
				// Empty array
64
				$table = array();
65
				// We not assume preprocessing here
66
				$checkstr = trim( $input );
67
				if ( !empty( $checkstr ) ) {
68
					$table = self::getCSVData( $input, $separator, $delimiter );
69
				}
70
71
				// wfErrorLog( "SELF: ".print_r($table), '/tmp/my-custom-debug.log' );
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
72
73
74
				foreach ( $table as $row ) {
75
					$fieldcount = 0;
76
					$struct = array();
77
					foreach ( $row as $field ) {
78
79
						$field = trim( $field );
80
						
81
						if ( ! empty( $field ) ) {
82
							$pretxt = "";
83
							if ( isset( $pre[ $fieldcount ] ) && !empty( $pre[ $fieldcount ] ) ) {
84
								$pretxt = $pre[ $fieldcount ].":"; // : for pre
85
							}
86
							$postxt = "";
87
							if ( isset( $post[ $fieldcount ] ) && !empty( $post[ $fieldcount ] ) ) {
88
								$postxt = "@".$post[ $fieldcount ]; // @ for post
89
							}
90
							if ( array_key_exists( $fieldcount, $fields ) ) {
91
								$struct[ $fields[ $fieldcount ] ] =  $pretxt.$field.$postxt;
92
							}
93
						}
94
						$fieldcount++;
95
					}
96
					foreach ( $dprops as $dpropk => $dpropv ) {
97
						$struct[ $dpropk ] = $dpropv;
98
					}
99
					
100
					SDImportData::insertInternalObject( $parser, $pageTitle, $object, $struct );
0 ignored issues
show
Documentation introduced by
$struct is of type array, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
101
				}
102
103
			}
104
105
		}
106
		
107
		if ( !empty( $input ) ) {
108
			$wgOut = $parser->getOutput();
109
110
			global $wgScriptPath;
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...
111
			$handsonpath = $wgScriptPath."/extensions/SemanticDataImport/libs/handsontable/handsontable.full.js";
112
			$wgOut->addHeadItem( '<script src="'.$handsonpath.'"></script>' ); //Hack because of handsontable for last versions :/
113
			$wgOut->addModules( 'ext.sdimport' );
114
115
			$fieldList = "";
116
			if ( sizeof( $fields ) > 0 ) {
117
				$fieldList = " data-cols='".implode(",", $fields)."' ";
118
			}
119
			
120
			$dataedit = "";
121
			if ( $editable ) {
0 ignored issues
show
Bug introduced by
The variable $editable 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...
122
				$dataedit = "data-edit='data-edit'";
123
			}
124
125
			$output = "<div class='smwdata' data-delimiter='".$delimiter."' data-separator=\"".$separator."\"".$fieldList." ".$dataedit.">".$input."</div>";
126
		}
127
128
		return array( $output, 'noparse' => true, 'isHTML' => true );
129
	}
130
131
132
133
	/**
134
	* @param $input string
135
	* @param $args array
136
	* @param $parser Parser
137
	* @param $frame Frame
138
	* @return string
139
	*/
140
	public static function prepareLink( $parser, $frame, $args ) {
141
142
		global $wgSDImportDataPage;
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...
143
144
		$wgOut = $parser->getOutput();
145
		$wgOut->addModules( 'ext.sdimport' );
146
		
147
		$attrs_allowed = array( "title", "model", "readonly", "ref", "readOnlyfields" );
148
		
149
		$attrs = array();
150
		$output = "";
151
		$model = "json"; // Let's use by default JSON model
152
		$pagetitle = null; // No page default. Do nothing
153
		$ref = null; // No ref hash by default
154
		$readOnlyfields = null; // No readonlyfields by default
155
		
156
		foreach ( $args as $arg ) {
157
			$arg_clean = trim( $frame->expand( $arg ) );
158
			$arg_proc = explode( "=", $arg_clean, 2 );
159
			
160
			if ( count( $arg_proc ) == 1 ){
161
				$pagetitle = trim( $arg_proc[0] );
162
			} else {
163
			
164
				if ( in_array( trim( $arg_proc[0] ), $attrs_allowed ) ) {
165
					$attrs[ trim( $arg_proc[0] ) ] = trim( $arg_proc[1] );
166
				}
167
			}
168
		}
169
		
170
		// TODO: Parse more parameters from function
171
		if ( array_key_exists( "title", $attrs ) ) {
172
			$pagetitle = $attrs['title'];
173
		}
174
		if ( array_key_exists( "model", $attrs ) ) {
175
			$model = $attrs['model'];
176
		}
177
		if ( array_key_exists( "ref", $attrs ) ) {
178
			$ref = str_replace( "[", "{", $attrs['ref'] );
179
			$ref = str_replace( "]", "}", $ref );
180
		}
181
182
		if ( array_key_exists( "readOnlyfields", $attrs ) ) {
183
			$readOnlyfields = str_replace( "[", "{", $attrs['readOnlyfields'] );
184
			$readOnlyfields = str_replace( "]", "}", $readOnlyfields );
185
		}
186
		
187
		if ( $pagetitle ) {
188
			
189
			$dataAttrsStr = "";
190
			
191
			if ( $pagetitle ) {
192
				$dataAttrsStr.= "data-title='$pagetitle'";
193
			}
194
			
195
			if ( $ref ) {
196
				$dataAttrsStr.= " data-ref='$ref'";
197
			}
198
			
199
			if ( $readOnlyfields ) {
200
				$dataAttrsStr.= " data-readOnlyfields='$readOnlyfields'";
201
			}
202
			
203
			$dataAttrsStr.= " data-model='$model'";
204
205
			if ( array_key_exists( "readonly", $attrs ) ) {
206
				$dataAttrsStr.= " data-readonly='true'";
207
			}
208
			
209
			$output = "<div class='smwdata-link' ".$dataAttrsStr."></div>";
210
		
211
		}
212
		
213
		return array( $output, 'noparse' => true, 'isHTML' => true );
214
		
215
	}
216
217
	private static function getCSVData( $text, $separator="\t", $delimiter='"' ) {
218
219
		$table = array();
220
221
		if ( empty( $text ) ) {
222
			return $table;
223
		}
224
225
		$linesCSV = explode( "\n", $text );
226
227
		foreach ( $linesCSV as $lineCSV ) {
228
			if ( !empty( $lineCSV ) ) {
229
				array_push( $table, str_getcsv( $lineCSV, $separator, $delimiter ) );
230
			}
231
		}
232
233
		return $table;
234
235
	}
236
237
238
239
}
240