Test Setup Failed
Branch gcconnex (718fe4)
by Ilia
20:37 queued 07:59
created

Inspector::getWidgets()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Elgg\Debug;
3
4
use Elgg\Debug\Inspector\ViewComponent;
5
6
/**
7
 * WARNING: API IN FLUX. DO NOT USE DIRECTLY.
8
 *
9
 * @access private
10
 *
11
 * @package Elgg.Core
12
 * @since   1.11
13
 */
14
class Inspector {
15
16
	/**
17
	 * Get Elgg event information
18
	 *
19
	 * @return array [event,type] => array(handlers)
20
	 */
21
	public function getEvents() {
22
		return $this->buildHandlerTree(_elgg_services()->events->getAllHandlers());
23
	}
24
25
	/**
26
	 * Get Elgg plugin hooks information
27
	 *
28
	 * @return array [hook,type] => array(handlers)
29
	 */
30
	public function getPluginHooks() {
31
		return $this->buildHandlerTree(_elgg_services()->hooks->getAllHandlers());
32
	}
33
34
	/**
35
	 * Get all view types for known views
36
	 *
37
	 * @return string[]
38
	 */
39
	public function getViewtypes() {
40
		global $CONFIG;
41
42
		return array_keys($CONFIG->views->locations);
43
	}
44
45
	/**
46
	 * Get Elgg view information
47
	 *
48
	 * @param string $viewtype The Viewtype we wish to inspect
49
	 *
50
	 * @return array [view] => map of priority to ViewComponent[]
51
	 */
52
	public function getViews($viewtype = 'default') {
53
		global $CONFIG;
54
55
		$overrides = null;
56
		if ($CONFIG->system_cache_enabled) {
57
			$data = _elgg_services()->systemCache->load('view_overrides');
58
			if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
59
				$overrides = unserialize($data);
60
			}
61
		} else {
62
			$overrides = _elgg_services()->views->getOverriddenLocations();
63
		}
64
65
		// maps view name to array of ViewComponent[] with priority as keys
66
		$views = array();
67
68
		$location = "{$CONFIG->viewpath}{$viewtype}/";
69
		$core_file_list = $this->recurseFileTree($location);
70
71
		// setup views array before adding extensions and plugin views
72
		foreach ($core_file_list as $path) {
73
			$component = ViewComponent::fromPaths($path, $location);
74
			$views[$component->view] = array(500 => $component);
75
		}
76
77
		// add plugins and handle overrides
78
		foreach ($CONFIG->views->locations[$viewtype] as $view => $location) {
79
			$component = new ViewComponent();
80
			$component->view = $view;
0 ignored issues
show
Documentation Bug introduced by
It seems like $view can also be of type integer. However, the property $view is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
81
			$component->location = "{$location}{$viewtype}/";
82
			$views[$view] = array(500 => $component);
83
		}
84
85
		// now extensions
86 View Code Duplication
		foreach ($CONFIG->views->extensions as $view => $extensions) {
87
			$view_list = array();
88
			foreach ($extensions as $priority => $ext_view) {
89
				if (isset($views[$ext_view])) {
90
					$view_list[$priority] = $views[$ext_view][500];
91
				}
92
			}
93
			if (count($view_list) > 0) {
94
				$views[$view] = $view_list;
95
			}
96
		}
97
98
		ksort($views);
99
100
		// now overrides
101
		foreach ($views as $view => $view_list) {
102
			if (!empty($overrides[$viewtype][$view])) {
103
				$overrides_list = array();
104
				foreach ($overrides[$viewtype][$view] as $i => $location) {
105
					$component = new ViewComponent();
106
					$component->overridden = true;
107
					$component->view = $view;
108
					$component->location = "{$location}{$viewtype}/";
109
					$overrides_list["o:$i"] = $component;
110
				}
111
				$views[$view] = $overrides_list + $view_list;
112
			}
113
		}
114
115
		// view handlers
116
		$handlers = _elgg_services()->hooks->getAllHandlers();
117
118
119
		$filtered_views = array();
120
		if (!empty($handlers['view'])) {
121
			$filtered_views = array_keys($handlers['view']);
122
		}
123
124
		$global_hooks = array();
125
		if (!empty($handlers['view']['all'])) {
126
			$global_hooks[] = 'view,all';
127
		}
128
		if (!empty($handlers['display']['view'])) {
129
			$global_hooks[] = 'display,view';
130
		}
131
		if (!empty($handlers['display']['all'])) {
132
			$global_hooks[] = 'display,all';
133
		}
134
135
		return array(
136
			'views' => $views,
137
			'global_hooks' => $global_hooks,
138
			'filtered_views' => $filtered_views,
139
		);
140
	}
141
142
	/**
143
	 * Get Elgg widget information
144
	 *
145
	 * @return array [widget] => array(name, contexts)
146
	 */
147 View Code Duplication
	public function getWidgets() {
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...
148
		$tree = array();
149
		foreach (_elgg_services()->widgets->getAllTypes() as $handler => $handler_obj) {
150
			$tree[$handler] = array($handler_obj->name, implode(',', array_values($handler_obj->context)));
151
		}
152
153
		ksort($tree);
154
155
		return $tree;
156
	}
157
158
159
	/**
160
	 * Get Elgg actions information
161
	 *
162
	 * returns [action] => array(file, access)
163
	 *
164
	 * @return array
165
	 */
166
	public function getActions() {
167
		$tree = array();
168
		$access = array(
169
			'public' => 'public',
170
			'logged_in' => 'logged in only',
171
			'admin' => 'admin only',
172
		);
173
		$start = strlen(elgg_get_root_path());
174
		foreach (_elgg_services()->actions->getAllActions() as $action => $info) {
175
			$info['file'] = substr($info['file'], $start);
176
			$tree[$action] = array($info['file'], $access[$info['access']]);
177
		}
178
		ksort($tree);
179
		return $tree;
180
	}
181
182
	/**
183
	 * Get simplecache information
184
	 *
185
	 * @return array [views]
186
	 */
187 View Code Duplication
	public function getSimpleCache() {
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...
188
		global $CONFIG;
189
190
		$tree = array();
191
		foreach ($CONFIG->views->simplecache as $view => $foo) {
192
			$tree[$view] = "";
193
		}
194
195
		ksort($tree);
196
197
		return $tree;
198
	}
199
200
	/**
201
	 * Get Elgg web services API methods
202
	 *
203
	 * @return array [method] => array(function, parameters, call_method, api auth, user auth)
204
	 */
205 View Code Duplication
	public function getWebServices() {
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...
206
		global $API_METHODS;
207
208
		$tree = array();
209
		foreach ($API_METHODS as $method => $info) {
210
			$params = implode(', ', array_keys($info['parameters']));
211
			if (!$params) {
212
				$params = 'none';
213
			}
214
			$tree[$method] = array(
215
				$info['function'],
216
				"params: $params",
217
				$info['call_method'],
218
				($info['require_api_auth']) ? 'API authentication required' : 'No API authentication required',
219
				($info['require_user_auth']) ? 'User authentication required' : 'No user authentication required',
220
			);
221
		}
222
223
		ksort($tree);
224
225
		return $tree;
226
	}
227
228
	/**
229
	 * Get information about registered menus
230
	 *
231
	 * @return array [menu name] => array(item name => array(text, href, section, parent))
232
	 */
233 View Code Duplication
	public function getMenus() {
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...
234
235
		$menus = elgg_get_config('menus');
236
237
		// get JIT menu items
238
		// note that 'river' is absent from this list - hooks attempt to get object/subject entities cause problems
239
		$jit_menus = array('annotation', 'entity', 'login', 'longtext', 'owner_block', 'user_hover', 'widget');
240
241
		// create generic ElggEntity, ElggAnnotation, ElggUser, ElggWidget
242
		$annotation = new \ElggAnnotation();
243
		$annotation->id = 999;
244
		$annotation->name = 'generic_comment';
245
		$annotation->value = 'testvalue';
246
247
		$entity = new \ElggObject();
248
		$entity->guid = 999;
249
		$entity->subtype = 'blog';
250
		$entity->title = 'test entity';
251
		$entity->access_id = ACCESS_PUBLIC;
252
253
		$user = new \ElggUser();
254
		$user->guid = 999;
255
		$user->name = "Test User";
256
		$user->username = 'test_user';
257
258
		$widget = new \ElggWidget();
259
		$widget->guid = 999;
260
		$widget->title = 'test widget';
261
262
		// call plugin hooks
263
		foreach ($jit_menus as $type) {
264
			$params = array('entity' => $entity, 'annotation' => $annotation, 'user' => $user);
265
			switch ($type){
266
				case 'owner_block':
267
				case 'user_hover':
268
					$params['entity'] = $user;
269
					break;
270
				case 'widget':
271
					// this does not work because you cannot set a guid on an entity
272
					$params['entity'] = $widget;
273
					break;
274
				default:
275
					break;
276
			}
277
			$menus[$type] = elgg_trigger_plugin_hook('register', "menu:$type", $params, array());
278
		}
279
280
		// put the menus in tree form for inspection
281
		$tree = array();
282
283
		foreach ($menus as $menu_name => $attributes) {
284
			foreach ($attributes as $item) {
285
				/* @var \ElggMenuItem $item */
286
				$name = $item->getName();
287
				$text = htmlspecialchars($item->getText(), ENT_QUOTES, 'UTF-8', false);
288
				$href = $item->getHref();
289
				if ($href === false) {
290
					$href = 'not a link';
291
				} elseif ($href === "") {
292
					$href = 'not a direct link - possibly ajax';
293
				}
294
				$section = $item->getSection();
295
				$parent = $item->getParentName();
296
				if (!$parent) {
297
					$parent = 'none';
298
				}
299
300
				$tree[$menu_name][$name] = array(
301
					"text: $text",
302
					"href: $href",
303
					"section: $section",
304
					"parent: $parent",
305
				);
306
			}
307
		}
308
309
		ksort($tree);
310
311
		return $tree;
312
	}
313
314
	/**
315
	 * Get a string description of a callback
316
	 *
317
	 * E.g. "function_name", "Static::method", "(ClassName)->method", "(Closure path/to/file.php:23)"
318
	 *
319
	 * @param mixed  $callable  The callable value to describe
320
	 * @param string $file_root if provided, it will be removed from the beginning of file names
321
	 * @return string
322
	 */
323
	public function describeCallable($callable, $file_root = '') {
324
		if (is_string($callable)) {
325
			return $callable;
326
		}
327
		if (is_array($callable) && array_keys($callable) === array(0, 1) && is_string($callable[1])) {
328
			if (is_string($callable[0])) {
329
				return "{$callable[0]}::{$callable[1]}";
330
			}
331
			return "(" . get_class($callable[0]) . ")->{$callable[1]}";
332
		}
333
		if ($callable instanceof \Closure) {
334
			$ref = new \ReflectionFunction($callable);
335
			$file = $ref->getFileName();
336
			$line = $ref->getStartLine();
337
338
			if ($file_root && 0 === strpos($file, $file_root)) {
339
				$file = substr($file, strlen($file_root));
340
			}
341
342
			return "(Closure {$file}:{$line})";
343
		}
344
		if (is_object($callable)) {
345
			return "(" . get_class($callable) . ")->__invoke()";
346
		}
347
		return "(unknown)";
348
	}
349
350
	/**
351
	 * Build a tree of event handlers
352
	 *
353
	 * @param array $all_handlers Set of handlers from a HooksRegistrationService
354
	 *
355
	 * @return array
356
	 */
357
	protected function buildHandlerTree($all_handlers) {
358
		$tree = array();
359
		$root = elgg_get_root_path();
360
361
		foreach ($all_handlers as $hook => $types) {
362
			foreach ($types as $type => $handlers) {
363
				array_walk($handlers, function (&$callable, $priority) use ($root) {
364
					$description = $this->describeCallable($callable, $root);
365
					$callable = "$priority: $description";
366
				});
367
				$tree[$hook . ',' . $type] = $handlers;
368
			}
369
		}
370
371
		ksort($tree);
372
373
		return $tree;
374
	}
375
376
	/**
377
	 * Create array of all php files in directory and subdirectories
378
	 *
379
	 * @param string $dir full path to directory to begin search
380
	 * @return array of every php file in $dir or below in file tree
381
	 */
382 View Code Duplication
	protected function recurseFileTree($dir) {
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...
383
		$view_list = array();
384
385
		$handle = opendir($dir);
386
		while ($file = readdir($handle)) {
387
			if ($file[0] == '.') {
388
389
			} else if (is_dir($dir . $file)) {
390
				$view_list = array_merge($view_list, $this->recurseFileTree($dir . $file . "/"));
391
			} else {
392
				$extension = strrchr(trim($file, "/"), '.');
393
				if ($extension === ".php") {
394
					$view_list[] = $dir . $file;
395
				}
396
			}
397
		}
398
		closedir($handle);
399
400
		return $view_list;
401
	}
402
}
403