Completed
Push — fix-for-add-folder ( c1d355...a17c5c )
by Sam
07:30
created

CMSMenu::provideI18nEntities()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
1
<?php
2
/**
3
 * The object manages the main CMS menu. See {@link LeftAndMain::init()} for
4
 * example usage.
5
 *
6
 * The menu will be automatically populated with menu items for subclasses of
7
 * {@link LeftAndMain}. That is, for each class in the CMS that creates an
8
 * administration panel, a CMS menu item will be created. The default
9
 * configuration will also include a 'help' link to the SilverStripe user
10
 * documentation.
11
 *
12
 * Additional CMSMenu items can be added through {@link LeftAndMainExtension::init()}
13
 * extensions added to {@link LeftAndMain}.
14
 *
15
 * @package framework
16
 * @subpackage admin
17
 */
18
class CMSMenu extends Object implements IteratorAggregate, i18nEntityProvider {
19
20
	/**
21
	 * Sort by menu priority, highest to lowest
22
	 */
23
	const MENU_PRIORITY = 'menu_priority';
24
25
	/**
26
	 * Sort by url priority, highest to lowest
27
	 */
28
	const URL_PRIORITY = 'url_priority';
29
30
	/**
31
	 * An array of changes to be made to the menu items, in the order that the changes should be
32
	 * applied.  Each item is a map in one of the two forms:
33
	 *  - array('type' => 'add', 'item' => new CMSMenuItem(...) )
34
	 *  - array('type' => 'remove', 'code' => 'codename' )
35
	 */
36
	protected static $menu_item_changes = array();
37
38
	/**
39
	 * Set to true if clear_menu() is called, to indicate that the default menu shouldn't be
40
	 * included
41
	 */
42
	protected static $menu_is_cleared = false;
43
44
	/**
45
	 * Generate CMS main menu items by collecting valid
46
	 * subclasses of {@link LeftAndMain}
47
	 */
48
	public static function populate_menu() {
49
		self::$menu_is_cleared = false;
50
	}
51
52
	/**
53
	 * Add a LeftAndMain controller to the CMS menu.
54
	 *
55
	 * @param string $controllerClass The class name of the controller
56
	 * @return The result of the operation
57
	 * @todo A director rule is added when a controller link is added, but it won't be removed
58
	 *			when the item is removed. Functionality needed in {@link Director}.
59
	 */
60
	public static function add_controller($controllerClass) {
61
		if($menuItem = self::menuitem_for_controller($controllerClass)) {
62
			self::add_menu_item_obj($controllerClass, $menuItem);
63
		}
64
	}
65
66
	/**
67
	 * Return a CMSMenuItem to add the given controller to the CMSMenu
68
	 */
69
	protected static function menuitem_for_controller($controllerClass) {
70
		$urlBase      = Config::inst()->get($controllerClass, 'url_base', Config::FIRST_SET);
71
		$urlSegment   = Config::inst()->get($controllerClass, 'url_segment', Config::FIRST_SET);
72
		$menuPriority = Config::inst()->get($controllerClass, 'menu_priority', Config::FIRST_SET);
73
74
		// Don't add menu items defined the old way
75
		if($urlSegment === null && $controllerClass != "CMSMain") return;
76
77
		$link = Controller::join_links($urlBase, $urlSegment) . '/';
78
79
		// doesn't work if called outside of a controller context (e.g. in _config.php)
80
		// as the locale won't be detected properly. Use {@link LeftAndMain->MainMenu()} to update
81
		// titles for existing menu entries
82
		$defaultTitle = LeftAndMain::menu_title_for_class($controllerClass);
83
		$menuTitle = _t("{$controllerClass}.MENUTITLE", $defaultTitle);
84
85
		return new CMSMenuItem($menuTitle, $link, $controllerClass, $menuPriority);
86
	}
87
88
89
	/**
90
	 * Add an arbitrary URL to the CMS menu.
91
	 *
92
	 * @param string $code A unique identifier (used to create a CSS ID and its key in {@link $menu_items})
93
	 * @param string $menuTitle The link's title in the CMS menu
94
	 * @param string $url The url of the link
95
	 * @param integer $priority The menu priority (sorting order) of the menu item.  Higher priorities will be further
96
	 *                          left.
97
	 * @param array $attributes an array of attributes to include on the link.
98
	 *
99
	 * @return boolean The result of the operation.
100
	 */
101
	public static function add_link($code, $menuTitle, $url, $priority = -1, $attributes = null) {
102
		return self::add_menu_item($code, $menuTitle, $url, null, $priority, $attributes);
103
	}
104
105
	/**
106
	 * Add a navigation item to the main administration menu showing in the top bar.
107
	 *
108
	 * uses {@link CMSMenu::$menu_items}
109
	 *
110
	 * @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
111
	 * 					{@link remove_menu_item}. Also used as a CSS-class for icon customization.
112
	 * @param string $menuTitle Localized title showing in the menu bar
113
	 * @param string $url A relative URL that will be linked in the menu bar.
114
	 * @param string $controllerClass The controller class for this menu, used to check permisssions.
115
	 * 					If blank, it's assumed that this is public, and always shown to users who
116
	 * 					have the rights to access some other part of the admin area.
117
	 * @param array $attributes an array of attributes to include on the link.
118
	 *
119
	 * @return boolean Success
120
	 */
121
	public static function add_menu_item($code, $menuTitle, $url, $controllerClass = null, $priority = -1,
122
											$attributes = null) {
123
		// If a class is defined, then force the use of that as a code.  This helps prevent menu item duplication
124
		if($controllerClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $controllerClass 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...
125
			$code = $controllerClass;
126
		}
127
128
		return self::replace_menu_item($code, $menuTitle, $url, $controllerClass, $priority, $attributes);
129
	}
130
131
	/**
132
	 * Get a single menu item by its code value.
133
	 *
134
	 * @param string $code
135
	 * @return array
136
	 */
137
	public static function get_menu_item($code) {
138
		$menuItems = self::get_menu_items();
139
		return (isset($menuItems[$code])) ? $menuItems[$code] : false;
140
	}
141
142
	/**
143
	 * Get all menu entries.
144
	 *
145
	 * @return array
146
	 */
147
	public static function get_menu_items() {
148
		$menuItems = array();
149
150
		// Set up default menu items
151
		if(!self::$menu_is_cleared) {
152
			$cmsClasses = self::get_cms_classes();
153
			foreach($cmsClasses as $cmsClass) {
154
				$menuItem = self::menuitem_for_controller($cmsClass);
155
				if($menuItem) $menuItems[Convert::raw2htmlname(str_replace('\\', '-', $cmsClass))] = $menuItem;
156
			}
157
		}
158
159
		// Apply changes
160
		foreach(self::$menu_item_changes as $change) {
161
			switch($change['type']) {
162
				case 'add':
163
					$menuItems[$change['code']] = $change['item'];
164
					break;
165
166
				case 'remove':
167
					unset($menuItems[$change['code']]);
168
					break;
169
170
				default:
171
					user_error("Bad menu item change type {$change[type]}", E_USER_WARNING);
172
			}
173
		}
174
175
		// Sort menu items according to priority, then title asc
176
		$menuPriority = array();
177
		$menuTitle    = array();
178
		foreach($menuItems as $key => $menuItem) {
179
			$menuPriority[$key] = is_numeric($menuItem->priority) ? $menuItem->priority : 0;
180
			$menuTitle[$key]    = $menuItem->title;
181
		}
182
		array_multisort($menuPriority, SORT_DESC, $menuTitle, SORT_ASC, $menuItems);
183
184
		return $menuItems;
185
	}
186
187
	/**
188
	 * Get all menu items that the passed member can view.
189
	 * Defaults to {@link Member::currentUser()}.
190
	 *
191
	 * @param Member $member
192
	 * @return array
193
	 */
194
	public static function get_viewable_menu_items($member = null) {
195
		if(!$member && $member !== FALSE) {
196
			$member = Member::currentUser();
197
		}
198
199
		$viewableMenuItems = array();
200
		$allMenuItems = self::get_menu_items();
201
		if($allMenuItems) foreach($allMenuItems as $code => $menuItem) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $allMenuItems of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
202
			// exclude all items which have a controller to perform permission
203
			// checks on
204
			if($menuItem->controller) {
205
				$controllerObj = singleton($menuItem->controller);
206
				if(Controller::has_curr()) {
207
					// Necessary for canView() to have request data available,
208
					// e.g. to check permissions against LeftAndMain->currentPage()
209
					$controllerObj->setRequest(Controller::curr()->getRequest());
210
					if(!$controllerObj->canView($member)) continue;
211
				}
212
			}
213
214
			$viewableMenuItems[$code] = $menuItem;
215
		}
216
217
		return $viewableMenuItems;
218
	}
219
220
	/**
221
	 * Removes an existing item from the menu.
222
	 *
223
	 * @param string $code Unique identifier for this menu item
224
	 */
225
	public static function remove_menu_item($code) {
226
		self::$menu_item_changes[] = array('type' => 'remove', 'code' => $code);
227
	}
228
229
	/**
230
	 * Clears the entire menu
231
	 */
232
	public static function clear_menu() {
233
		self::$menu_item_changes = array();
234
		self::$menu_is_cleared = true;
235
	}
236
237
	/**
238
	 * Replace a navigation item to the main administration menu showing in the top bar.
239
	 *
240
	 * @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
241
	 * 					{@link remove_menu_item}. Also used as a CSS-class for icon customization.
242
	 * @param string $menuTitle Localized title showing in the menu bar
243
	 * @param string $url A relative URL that will be linked in the menu bar.
244
	 * 					Make sure to add a matching route via {@link Director::$rules} to this url.
245
	 * @param string $controllerClass The controller class for this menu, used to check permisssions.
246
	 * 					If blank, it's assumed that this is public, and always shown to users who
247
	 * 					have the rights to access some other part of the admin area.
248
	 * @param array $attributes an array of attributes to include on the link.
249
	 *
250
	 * @return boolean Success
251
	 */
252
	public static function replace_menu_item($code, $menuTitle, $url, $controllerClass = null, $priority = -1,
253
												$attributes = null) {
254
		$item = new CMSMenuItem($menuTitle, $url, $controllerClass, $priority);
255
256
		if($attributes) {
257
			$item->setAttributes($attributes);
258
		}
259
260
		self::$menu_item_changes[] = array(
261
			'type' => 'add',
262
			'code' => $code,
263
			'item' => $item,
264
		);
265
	}
266
267
	/**
268
	 * Add a previously built menu item object to the menu
269
	 */
270
	protected static function add_menu_item_obj($code, $cmsMenuItem) {
271
		self::$menu_item_changes[] = array(
272
			'type' => 'add',
273
			'code' => $code,
274
			'item' => $cmsMenuItem,
275
		);
276
	}
277
278
	/**
279
	 * A utility funciton to retrieve subclasses of a given class that
280
	 * are instantiable (ie, not abstract) and have a valid menu title.
281
	 *
282
	 * Sorted by url_priority config.
283
	 *
284
	 * @todo A variation of this function could probably be moved to {@link ClassInfo}
285
	 * @param string $root The root class to begin finding subclasses
286
	 * @param boolean $recursive Look for subclasses recursively?
287
	 * @param string $sort Name of config on which to sort. Can be 'menu_priority' or 'url_priority'
288
	 * @return array Valid, unique subclasses
289
	 */
290
	public static function get_cms_classes($root = null, $recursive = true, $sort = self::MENU_PRIORITY) {
291
		if(!$root) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $root of type string|null is loosely compared to false; 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...
292
			$root = 'LeftAndMain';
293
		}
294
		$subClasses = array_values(ClassInfo::subclassesFor($root));
295
		foreach($subClasses as $className) {
296
			if($recursive && $className != $root) {
297
				$subClasses = array_merge($subClasses, array_values(ClassInfo::subclassesFor($className)));
298
			}
299
		}
300
		$subClasses = array_unique($subClasses);
301
		foreach($subClasses as $key => $className) {
302
			// Remove abstract classes and LeftAndMain
303
			if('LeftAndMain' == $className || ClassInfo::classImplements($className, 'TestOnly')) {
304
				unset($subClasses[$key]);
305
			} else {
306
				// Separate conditional to avoid autoloading the class
307
				$classReflection = new ReflectionClass($className);
308
				if(!$classReflection->isInstantiable()) {
309
					unset($subClasses[$key]);
310
				}
311
			}
312
		}
313
314
		// Sort by specified sorting config
315
		usort($subClasses, function ($a, $b) use ($sort) {
316
			$priorityA = Config::inst()->get($a, $sort);
317
			$priorityB = Config::inst()->get($b, $sort);
318
			return $priorityB - $priorityA;
319
		});
320
321
		return $subClasses;
322
	}
323
324
	/**
325
	 * IteratorAggregate Interface Method.  Iterates over the menu items.
326
	 */
327
	public function getIterator() {
328
		return new ArrayIterator(self::get_menu_items());
329
	}
330
331
	/**
332
	 * Provide menu titles to the i18n entity provider
333
	 */
334
	public function provideI18nEntities() {
335
		$cmsClasses = self::get_cms_classes();
336
		$entities = array();
337
		foreach($cmsClasses as $cmsClass) {
338
			$defaultTitle = LeftAndMain::menu_title_for_class($cmsClass);
339
			$ownerModule = i18n::get_owner_module($cmsClass);
340
			$entities["{$cmsClass}.MENUTITLE"] = array($defaultTitle, 'Menu title', $ownerModule);
341
		}
342
		return $entities;
343
	}
344
}
345