Completed
Push — master ( 977272...11f4a6 )
by Karsten
07:17
created

SemanticResultFormats::onExtensionFunction()   C

Complexity

Conditions 9
Paths 10

Size

Total Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 91
rs 6.6408
c 0
b 0
f 0
cc 9
nc 10
nop 0

How to fix   Long Method   

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
0 ignored issues
show
Coding Style Compatibility introduced by Jeroen De Dauw
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 14 and the first side effect is on line 9.

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
/**
4
 * @see https://github.com/SemanticMediaWiki/SemanticResultFormats/
5
 *
6
 * @defgroup SRF Semantic Result Formats
7
 */
8
9
SemanticResultFormats::load();
10
11
/**
12
 * @codeCoverageIgnore
13
 */
14
class SemanticResultFormats {
15
16
	/**
17
	 * @since 2.5
18
	 *
19
	 * @note It is expected that this function is loaded before LocalSettings.php
20
	 * to ensure that settings and global functions are available by the time
21
	 * the extension is activated.
22
	 */
23
	public static function load() {
24
25
		if ( is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
26
			include_once __DIR__ . '/vendor/autoload.php';
27
		}
28
29
		// Load DefaultSettings
30
		require_once __DIR__ . '/DefaultSettings.php';
31
	}
32
33
	/**
34
	 * @since 2.5
35
	 */
36
	public static function initExtension() {
0 ignored issues
show
Coding Style introduced by mwjames
initExtension uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
37
38
		// See https://phabricator.wikimedia.org/T151136
39
		define( 'SRF_VERSION', isset( $credits['version'] ) ? $credits['version'] : 'UNKNOWN' );
0 ignored issues
show
Bug introduced by Karsten Hoffmeyer
The variable $credits seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
40
41
		// Register message files
42
		$GLOBALS['wgMessagesDirs']['SemanticResultFormats'] = __DIR__ . '/i18n';
43
		$GLOBALS['wgExtensionMessagesFiles']['SemanticResultFormats'] = __DIR__ . '/SemanticResultFormats.i18n.php';
44
		$GLOBALS['wgExtensionMessagesFiles']['SemanticResultFormatsMagic'] = __DIR__ . '/SemanticResultFormats.i18n.magic.php';
45
46
		$GLOBALS['srfgIP'] = __DIR__;
47
		$GLOBALS['wgResourceModules'] = array_merge( $GLOBALS['wgResourceModules'], include( __DIR__ . "/Resources.php" ) );
48
49
		self::registerHooks();
50
	}
51
52
	/**
53
	 * @since 2.5
54
	 */
55
	public static function registerHooks() {
0 ignored issues
show
Coding Style introduced by mwjames
registerHooks uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
56
		$formatDir = __DIR__ . '/formats/';
57
58
		unset( $formatDir );
59
60
		$GLOBALS['wgHooks']['ParserFirstCallInit'][] = 'SRFParserFunctions::registerFunctions';
61
		$GLOBALS['wgHooks']['UnitTestsList'][] = 'SRFHooks::registerUnitTests';
62
63
		$GLOBALS['wgHooks']['ResourceLoaderTestModules'][] = 'SRFHooks::registerQUnitTests';
64
		$GLOBALS['wgHooks']['ResourceLoaderGetConfigVars'][] = 'SRFHooks::onResourceLoaderGetConfigVars';
65
66
		// Format hooks
67
		$GLOBALS['wgHooks']['OutputPageParserOutput'][] = 'SRF\Filtered\Hooks::onOutputPageParserOutput';
68
		$GLOBALS['wgHooks']['MakeGlobalVariablesScript'][] = 'SRF\Filtered\Hooks::onMakeGlobalVariablesScript';
69
70
		// register API modules
71
		$GLOBALS['wgAPIModules']['ext.srf.slideshow.show'] = 'SRFSlideShowApi';
72
73
		// User preference
74
		$GLOBALS['wgHooks']['SMW::GetPreferences'][] = 'SRFHooks::onGetPreferences';
75
76
		// Allows last minute changes to the output page, e.g. adding of CSS or JavaScript by extensions
77
		$GLOBALS['wgHooks']['BeforePageDisplay'][] = 'SRFHooks::onBeforePageDisplay';
78
	}
79
80
	/**
81
	 * @since 2.5
82
	 */
83
	public static function onExtensionFunction() {
0 ignored issues
show
Coding Style introduced by mwjames
onExtensionFunction uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
84
85
		if ( !defined( 'SMW_VERSION' ) ) {
86
87
			if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
88
				die( "\nThe 'Semantic Result Formats' extension requires 'Semantic MediaWiki' to be installed and enabled.\n" );
0 ignored issues
show
Coding Style Compatibility introduced by Karsten Hoffmeyer
The method onExtensionFunction() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
89
			} else {
90
				die(
0 ignored issues
show
Coding Style Compatibility introduced by Karsten Hoffmeyer
The method onExtensionFunction() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
91
					'<b>Error:</b> The <a href="https://github.com/SemanticMediaWiki/SemanticResultFormats/">Semantic Result Formats</a> ' .
92
					'extension requires <a href="https://www.semantic-mediawiki.org/wiki/Semantic_MediaWiki">Semantic MediaWiki</a> to be ' .
93
					'installed and enabled.<br />'
94
				);
95
			}
96
		}
97
98
		// Admin Links hook needs to be called in a delayed way so that it
99
		// will always be called after SMW's Admin Links addition; as of
100
		// SMW 1.9, SMW delays calling all its hook functions.
101
		$GLOBALS['wgHooks']['AdminLinks'][] = 'SRFHooks::addToAdminLinks';
102
103
		$GLOBALS['srfgScriptPath'] = ( $GLOBALS['wgExtensionAssetsPath'] === false ? $GLOBALS['wgScriptPath'] . '/extensions' : $GLOBALS['wgExtensionAssetsPath'] ) . '/SemanticResultFormats';
104
105
		$formatClasses = [
106
			// Assign the Boilerplate class to a format identifier
107
			// 'boilerplate' => 'SRFBoilerplate',
108
			'timeline' => 'SRFTimeline',
109
			'eventline' => 'SRFTimeline',
110
			'vcard' => 'SRF\vCard\vCardFileExportPrinter',
111
			'icalendar' => 'SRF\iCalendar\iCalendarFileExportPrinter',
112
			'bibtex' => 'SRFBibTeX',
113
			'calendar' => 'SRFCalendar',
114
			'eventcalendar' => 'SRF\EventCalendar',
115
			'outline' => 'SRFOutline',
116
			'sum' => 'SRFMath',
117
			'product' => 'SRFMath',
118
			'average' => 'SRFMath',
119
			'min' => 'SRFMath',
120
			'max' => 'SRFMath',
121
			'median' => 'SRFMath',
122
			'exhibit' => 'SRFExhibit',
123
			'googlebar' => 'SRFGoogleBar',
124
			'googlepie' => 'SRFGooglePie',
125
			'jitgraph' => 'SRFJitGraph',
126
			'jqplotchart' => 'SRFjqPlotChart',
127
			'jqplotseries' => 'SRFjqPlotSeries',
128
			'graph' => 'SRFGraph',
129
			'process' => 'SRFProcess',
130
			'gallery' => 'SRF\Gallery',
131
			'tagcloud' => 'SRF\TagCloud',
132
			'valuerank' => 'SRFValueRank',
133
			'array' => 'SRFArray',
134
			'hash' => 'SRFHash',
135
			'd3chart' => 'SRFD3Chart',
136
			'tree' => 'SRF\Formats\Tree\TreeResultPrinter',
137
			'ultree' => 'SRF\Formats\Tree\TreeResultPrinter',
138
			'oltree' => 'SRF\Formats\Tree\TreeResultPrinter',
139
			'filtered' => 'SRF\Filtered\Filtered',
140
			'latest' => 'SRFTime',
141
			'earliest' => 'SRFTime',
142
			'slideshow' => 'SRFSlideShow',
143
			'timeseries' => 'SRFTimeseries',
144
			'sparkline' => 'SRFSparkline',
145
			'listwidget' => 'SRFListWidget',
146
			'pagewidget' => 'SRFPageWidget',
147
			'dygraphs' => 'SRFDygraphs',
148
			'incoming' => 'SRFIncoming',
149
			'media' => 'SRF\MediaPlayer',
150
			'excel' => 'SRF\SRFExcel',
151
			'datatables' => 'SRF\DataTables'
152
		];
153
154
		$formatAliases = [
155
			'tagcloud'   => [ 'tag cloud' ],
156
			'datatables'   => [ 'datatable' ],
157
			'valuerank'  => [ 'value rank' ],
158
			'd3chart'    => [ 'd3 chart' ],
159
			'timeseries' =>  [ 'time series' ],
160
			'jqplotchart' => [ 'jqplot chart', 'jqplotpie', 'jqplotbar' ],
161
			'jqplotseries' => [ 'jqplot series' ],
162
		];
163
164
		foreach ( $GLOBALS['srfgFormats'] as $format ) {
0 ignored issues
show
Bug introduced by mwjames
The expression $GLOBALS['srfgFormats'] of type string|null 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...
165
			if ( array_key_exists( $format, $formatClasses ) ) {
166
				$GLOBALS['smwgResultFormats'][$format] = $formatClasses[$format];
167
168
				if ( isset( $GLOBALS['smwgResultAliases'] ) && array_key_exists( $format, $formatAliases ) ) {
169
					$GLOBALS['smwgResultAliases'][$format] = $formatAliases[$format];
170
				}
171
			}
172
		}
173
	}
174
175
	/**
176
	 * @since 2.5
177
	 *
178
	 * @return string|null
179
	 */
180
	public static function getVersion() {
181
		return SRF_VERSION;
182
	}
183
184
}
185