GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 9df84b...567f57 )
by Shea
02:05
created

BlocksSiteTreeExtension   F

Complexity

Total Complexity 55

Size/Duplication

Total Lines 313
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 34
Bugs 3 Features 10
Metric Value
wmc 55
c 34
b 3
f 10
lcom 1
cbo 18
dl 0
loc 313
rs 2.9203

9 Methods

Rating   Name   Duplication   Size   Complexity  
B showBlocksFields() 0 19 5
C updateCMSFields() 0 63 9
D BlockArea() 0 33 9
B HasBlockArea() 0 16 6
D getBlockList() 0 36 10
D getAppliedSets() 0 35 9
B getBlocksFromAppliedBlockSets() 0 27 5
A areasPreviewLink() 0 4 1
A areasPreviewButton() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like BlocksSiteTreeExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BlocksSiteTreeExtension, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * BlocksSiteTreeExtension.
4
 *
5
 * @author Shea Dawson <[email protected]>
6
 */
7
class BlocksSiteTreeExtension extends SiteTreeExtension
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...
8
{
9
	private static $db = array(
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
10
		'InheritBlockSets' => 'Boolean',
11
	);
12
	private static $many_many = array(
0 ignored issues
show
Unused Code introduced by
The property $many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
		'Blocks' => 'Block',
14
		'DisabledBlocks' => 'Block',
15
	);
16
	public static $many_many_extraFields = array(
17
		'Blocks' => array(
18
			'Sort' => 'Int',
19
			'BlockArea' => 'Varchar',
20
		),
21
	);
22
	private static $defaults = array(
0 ignored issues
show
Unused Code introduced by
The property $defaults is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
23
		'InheritBlockSets' => 1,
24
	);
25
	private static $dependencies = array(
0 ignored issues
show
Unused Code introduced by
The property $dependencies is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
26
		'blockManager' => '%$blockManager',
27
	);
28
	public $blockManager;
29
30
31
	/**
32
	 * Check if the Blocks CMSFields should be displayed for this Page
33
	 *
34
	 * @return boolean
35
	 **/
36
	public function showBlocksFields()
37
	{
38
		$whiteList = $this->blockManager->getWhiteListedPageTypes();
39
		$blackList = $this->blockManager->getBlackListedPageTypes();
40
41
		if (in_array($this->owner->ClassName, $blackList)) {
42
			return false;
43
		}
44
45
		if (count($whiteList) && !in_array($this->owner->ClassName, $whiteList)) {
46
			return false;
47
		}
48
49
		if (!Permission::check('BLOCK_EDIT')) {
50
			return false;
51
		}
52
53
		return true;
54
	}
55
56
	/**
57
	 * Block manager for Pages.
58
	 * */
59
	public function updateCMSFields(FieldList $fields)
60
	{
61
		if ($fields->fieldByName('Root.Blocks') || !$this->showBlocksFields()) {
62
			return;
63
		}
64
65
		$areas = $this->blockManager->getAreasForPageType($this->owner->ClassName);
66
67
		if ($areas && count($areas)) {
68
			$fields->addFieldToTab('Root', new Tab('Blocks', _t('Block.PLURALNAME')));
69
			if (BlockManager::config()->get('block_area_preview')) {
70
				$fields->addFieldToTab('Root.Blocks',
71
						LiteralField::create('PreviewLink', $this->areasPreviewButton()));
72
			}
73
74
			// Blocks related directly to this Page
75
			$gridConfig = GridFieldConfig_BlockManager::create(true, true, true, true)
76
				->addExisting($this->owner->class)
0 ignored issues
show
Unused Code introduced by
The call to GridFieldConfig_BlockManager::addExisting() has too many arguments starting with $this->owner->class.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
77
				//->addBulkEditing()
78
				->addComponent(new GridFieldOrderableRows())
79
				;
80
81
			// TODO it seems this sort is not being applied...
82
			$gridSource = $this->owner->Blocks();
83
				// ->sort(array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
84
				// 	"FIELD(SiteTree_Blocks.BlockArea, '" . implode("','", array_keys($areas)) . "')" => '',
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
85
				// 	'SiteTree_Blocks.Sort' => 'ASC',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
86
				// 	'Name' => 'ASC'
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
87
				// ));
88
89
			$fields->addFieldToTab('Root.Blocks', GridField::create('Blocks', _t('Block.PLURALNAME', 'Blocks'), $gridSource, $gridConfig));
90
91
			// Blocks inherited from BlockSets
92
			if ($this->blockManager->getUseBlockSets()) {
93
				$inheritedBlocks = $this->getBlocksFromAppliedBlockSets(null, true);
94
95
				if ($inheritedBlocks->count()) {
96
					$activeInherited = $this->getBlocksFromAppliedBlockSets(null, false);
97
98
					if ($activeInherited->count()) {
99
						$fields->addFieldsToTab('Root.Blocks', array(
100
							GridField::create('InheritedBlockList', _t('BlocksSiteTreeExtension.BlocksInheritedFromBlockSets', 'Blocks Inherited from Block Sets'), $activeInherited,
101
								GridFieldConfig_BlockManager::create(false, false, false)),
102
							LiteralField::create('InheritedBlockListTip', "<p class='message'>"._t('BlocksSiteTreeExtension.InheritedBlocksEditLink', 'Tip: Inherited blocks can be edited in the {link_start}Block Admin area{link_end}', '', array('link_start' => '<a href="admin/block-admin">', 'link_end' => '</a>')).'<p>'),
0 ignored issues
show
Documentation introduced by
array('link_start' => '<..., 'link_end' => '</a>') is of type array<string,string,{"li...","link_end":"string"}>, but the function expects a string.

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...
103
						));
104
					}
105
106
					$fields->addFieldToTab('Root.Blocks',
107
							ListBoxField::create('DisabledBlocks', _t('BlocksSiteTreeExtension.DisableInheritedBlocks', 'Disable Inherited Blocks'),
108
									$inheritedBlocks->map('ID', 'Title'), null, null, true)
109
									->setDescription(_t('BlocksSiteTreeExtension.DisableInheritedBlocksDescription', 'Select any inherited blocks that you would not like displayed on this page.'))
110
					);
111
				} else {
112
					$fields->addFieldToTab('Root.Blocks',
113
							ReadonlyField::create('DisabledBlocksReadOnly', _t('BlocksSiteTreeExtension.DisableInheritedBlocks', 'Disable Inherited Blocks'),
114
									_t('BlocksSiteTreeExtension.NoInheritedBlocksToDisable','This page has no inherited blocks to disable.')));
115
				}
116
117
				$fields->addFieldToTab('Root.Blocks',
118
					CheckboxField::create('InheritBlockSets', _t('BlocksSiteTreeExtension.InheritBlocksFromBlockSets', 'Inherit Blocks from Block Sets')));
119
			}
120
		}
121
	}
122
123
	/**
124
	 * Called from templates to get rendered blocks for the given area.
125
	 *
126
	 * @param string $area
127
	 * @param int    $limit Limit the items to this number, or null for no limit
128
	 */
129
	public function BlockArea($area, $limit = null)
0 ignored issues
show
Coding Style introduced by
BlockArea uses the super-global variable $_REQUEST 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...
130
	{
131
		if ($this->owner->ID <= 0) {
132
			return;
133
		} // blocks break on fake pages ie Security/login
134
135
		$list = $this->getBlockList($area);
136
137
		foreach ($list as $block) {
138
			if (!$block->canView()) {
139
				$list->remove($block);
140
			}
141
		}
142
143
		if ($limit !== null) {
144
			$list = $list->limit($limit);
145
		}
146
147
		$data = array();
148
		$data['HasBlockArea'] = ($this->owner->canEdit() && isset($_REQUEST['block_preview']) && $_REQUEST['block_preview']) || $list->Count() > 0;
149
		$data['BlockArea'] = $list;
150
		$data['AreaID'] = $area;
151
152
		$data = $this->owner->customise($data);
153
154
		$template = array('BlockArea_'.$area);
155
156
		if (SSViewer::hasTemplate($template)) {
157
			return $data->renderWith($template);
158
		} else {
159
			return $data->renderWith('BlockArea');
160
		}
161
	}
162
163
	public function HasBlockArea($area)
0 ignored issues
show
Coding Style introduced by
HasBlockArea uses the super-global variable $_REQUEST 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...
164
	{
165
		if ($this->owner->canEdit() && isset($_REQUEST['block_preview']) && $_REQUEST['block_preview']) {
166
			return true;
167
		}
168
169
		$list = $this->getBlockList($area);
170
171
		foreach ($list as $block) {
172
			if (!$block->canView()) {
173
				$list->remove($block);
174
			}
175
		}
176
177
		return $list->Count() > 0;
178
	}
179
180
	/**
181
	 * Get a merged list of all blocks on this page and ones inherited from BlockSets.
182
	 *
183
	 * @param string|null $area            filter by block area
184
	 * @param bool        $includeDisabled Include blocks that have been explicitly excluded from this page
185
	 *                                     i.e. blocks from block sets added to the "disable inherited blocks" list
186
	 *
187
	 * @return ArrayList
188
	 * */
189
	public function getBlockList($area = null, $includeDisabled = false)
190
	{
191
		$includeSets = $this->blockManager->getUseBlockSets() && $this->owner->InheritBlockSets;
192
		$blocks = ArrayList::create();
193
194
		// get blocks directly linked to this page
195
		$nativeBlocks = $this->owner->Blocks()->sort('Sort');
196
		if ($area) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $area 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...
197
			$nativeBlocks = $nativeBlocks->filter('BlockArea', $area);
198
		}
199
200
		if ($nativeBlocks->count()) {
201
			foreach ($nativeBlocks as $block) {
202
				$blocks->add($block);
203
			}
204
		}
205
206
		// get blocks from BlockSets
207
		if ($includeSets) {
208
			$blocksFromSets = $this->getBlocksFromAppliedBlockSets($area, $includeDisabled);
209
			if ($blocksFromSets->count()) {
210
				// merge set sources
211
				foreach ($blocksFromSets as $block) {
212
					if (!$blocks->find('ID', $block->ID)) {
213
						if ($block->AboveOrBelow == 'Above') {
214
							$blocks->unshift($block);
215
						} else {
216
							$blocks->push($block);
217
						}
218
					}
219
				}
220
			}
221
		}
222
223
		return $blocks;
224
	}
225
226
	/**
227
	 * Get Any BlockSets that apply to this page.
228
	 *
229
	 * @return ArrayList
230
	 * */
231
	public function getAppliedSets()
232
	{
233
		$list = ArrayList::create();
234
		if (!$this->owner->InheritBlockSets) {
235
			return $list;
236
		}
237
238
		$sets = BlockSet::get()->where("(PageTypesValue IS NULL) OR (PageTypesValue LIKE '%:\"{$this->owner->ClassName}%')");
239
		$ancestors = $this->owner->getAncestors()->column('ID');
240
241
		foreach ($sets as $set) {
242
			$restrictedToParerentIDs = $set->PageParents()->column('ID');
243
			if (count($restrictedToParerentIDs)) {
244
				// check whether the set should include selected parent, in which case check whether
245
				// it was in the restricted parents list. If it's not, or if include parentpage
246
				// wasn't selected, we check the ancestors of this page.
247
				if ($set->IncludePageParent && in_array($this->owner->ID, $restrictedToParerentIDs)) {
248
					$list->add($set);
249
				} else {
250
					if (count($ancestors)) {
251
						foreach ($ancestors as $ancestor) {
252
							if (in_array($ancestor, $restrictedToParerentIDs)) {
253
								$list->add($set);
254
								continue;
255
							}
256
						}
257
					}
258
				}
259
			} else {
260
				$list->add($set);
261
			}
262
		}
263
264
		return $list;
265
	}
266
267
	/**
268
	 * Get all Blocks from BlockSets that apply to this page.
269
	 *
270
	 * @return ArrayList
271
	 * */
272
	public function getBlocksFromAppliedBlockSets($area = null, $includeDisabled = false)
273
	{
274
		$blocks = ArrayList::create();
275
		$sets = $this->getAppliedSets();
276
277
		if (!$sets->count()) {
278
			return $blocks;
279
		}
280
281
		foreach ($sets as $set) {
282
			$setBlocks = $set->Blocks()->sort('Sort DESC');
283
284
			if (!$includeDisabled) {
285
				$setBlocks = $setBlocks->exclude('ID', $this->owner->DisabledBlocks()->column('ID'));
286
			}
287
288
			if ($area) {
289
				$setBlocks = $setBlocks->filter('BlockArea', $area);
290
			}
291
292
			$blocks->merge($setBlocks);
293
		}
294
295
		$blocks->removeDuplicates();
296
297
		return $blocks;
298
	}
299
300
	/**
301
	 * Get's the link for a block area preview button.
302
	 *
303
	 * @return string
304
	 * */
305
	public function areasPreviewLink()
306
	{
307
		return Controller::join_links($this->owner->Link(), '?block_preview=1');
308
	}
309
310
	/**
311
	 * Get's html for a block area preview button.
312
	 *
313
	 * @return string
314
	 * */
315
	public function areasPreviewButton()
316
	{
317
		return "<a class='ss-ui-button ss-ui-button-small' style='font-style:normal;' href='".$this->areasPreviewLink()."' target='_blank'>"._t('BlocksSiteTreeExtension.PreviewBlockAreasLink', 'Preview Block Areas for this page').'</a>';
318
	}
319
}
320