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
Pull Request — master (#111)
by
unknown
03:02
created

BlocksSiteTreeExtension::getAppliedSets()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 4.909
c 0
b 0
f 0
cc 9
eloc 20
nc 8
nop 0
1
<?php
2
3
namespace SheaDawson\Blocks\extensions;
4
5
use SheaDawson\Blocks\BlockManager;
6
use SheaDawson\Blocks\model\Blockset;
7
use SheaDawson\Blocks\forms\GridFieldConfigBlockManager;
8
9
use SilverStripe\CMS\Model\SiteTreeExtension;
10
11
use SilverStripe\Forms\ReadonlyField;
12
use SilverStripe\Forms\CheckboxField;
13
use SilverStripe\Forms\FieldList;
14
15
use SilverStripe\View\SSViewer;
16
17
use SilverStripe\ORM\ArrayList;
18
19
use SilverStripe\Security\Permission;
20
21
use SilverStripe\Control\Controller;
22
23
/**
24
 * BlocksSiteTreeExtension.
25
 *
26
 * @author Shea Dawson <[email protected]>
27
 */
28
class BlocksSiteTreeExtension extends SiteTreeExtension
29
{
30
	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...
31
		'InheritBlockSets' => 'Boolean',
32
	);
33
	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...
34
		"Blocks" => "SheaDawson\Blocks\model\Block",
35
		"DisabledBlocks" => "SheaDawson\Blocks\model\Block",
36
	);
37
	public static $many_many_extraFields = array(
38
		'Blocks' => array(
39
			'Sort' => 'Int',
40
			'BlockArea' => 'Varchar',
41
		),
42
	);
43
	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...
44
		'InheritBlockSets' => 1,
45
	);
46
	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...
47
		'blockManager' => '%$SheaDawson\\Blocks\\BlockManager',
48
	);
49
50
	public $blockManager;
51
52
53
	/**
54
	 * Check if the Blocks CMSFields should be displayed for this Page
55
	 *
56
	 * @return boolean
57
	 **/
58
	public function showBlocksFields()
59
	{
60
		$whiteList = $this->blockManager->getWhiteListedPageTypes();
61
		$blackList = $this->blockManager->getBlackListedPageTypes();
62
63
		if (in_array($this->owner->ClassName, $blackList)) {
64
			return false;
65
		}
66
67
		if (count($whiteList) && !in_array($this->owner->ClassName, $whiteList)) {
68
			return false;
69
		}
70
71
		if (!Permission::check('BLOCK_EDIT')) {
72
			return false;
73
		}
74
75
		return true;
76
	}
77
78
	/**
79
	 * Block manager for Pages.
80
	 * */
81
	public function updateCMSFields(FieldList $fields)
82
	{
83
		if ($fields->fieldByName('Root.Blocks') || !$this->showBlocksFields()) {
84
			return;
85
		}
86
87
		$areas = $this->blockManager->getAreasForPageType($this->owner->ClassName);
88
89
		if ($areas && count($areas)) {
90
			$fields->addFieldToTab('Root', new Tab('Blocks', _t('Block.PLURALNAME', 'Blocks')));
91
			if (BlockManager::config()->get('block_area_preview')) {
92
				$fields->addFieldToTab('Root.Blocks',
93
						LiteralField::create('PreviewLink', $this->areasPreviewButton()));
94
			}
95
96
			// Blocks related directly to this Page
97
			$gridConfig = GridFieldConfigBlockManager::create(true, true, true, true)
98
				->addExisting($this->owner->class)
99
				//->addBulkEditing()
100
				->addComponent(new GridFieldOrderableRows())
101
				;
102
103
			// TODO it seems this sort is not being applied...
104
			$gridSource = $this->owner->Blocks();
105
				// ->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...
106
				// 	"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...
107
				// 	'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...
108
				// 	'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...
109
				// ));
110
111
			$fields->addFieldToTab('Root.Blocks', GridField::create('Blocks', _t('Block.PLURALNAME', 'Blocks'), $gridSource, $gridConfig));
112
113
			// Blocks inherited from BlockSets
114
			if ($this->blockManager->getUseBlockSets()) {
115
				$inheritedBlocks = $this->getBlocksFromAppliedBlockSets(null, true);
116
117
				if ($inheritedBlocks->count()) {
118
					$activeInherited = $this->getBlocksFromAppliedBlockSets(null, false);
119
120
					if ($activeInherited->count()) {
121
						$fields->addFieldsToTab('Root.Blocks', array(
122
							GridField::create('InheritedBlockList', _t('BlocksSiteTreeExtension.BlocksInheritedFromBlockSets', 'Blocks Inherited from Block Sets'), $activeInherited,
123
								GridFieldConfigBlockManager::create(false, false, false)),
124
							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...
125
						));
126
					}
127
128
					$fields->addFieldToTab('Root.Blocks',
129
							ListBoxField::create('DisabledBlocks', _t('BlocksSiteTreeExtension.DisableInheritedBlocks', 'Disable Inherited Blocks'),
130
									$inheritedBlocks->map('ID', 'Title'), null, null, true)
131
									->setDescription(_t('BlocksSiteTreeExtension.DisableInheritedBlocksDescription', 'Select any inherited blocks that you would not like displayed on this page.'))
132
					);
133
				} else {
134
					$fields->addFieldToTab('Root.Blocks',
135
							ReadonlyField::create('DisabledBlocksReadOnly', _t('BlocksSiteTreeExtension.DisableInheritedBlocks', 'Disable Inherited Blocks'),
136
									_t('BlocksSiteTreeExtension.NoInheritedBlocksToDisable','This page has no inherited blocks to disable.')));
137
				}
138
139
				$fields->addFieldToTab('Root.Blocks',
140
					CheckboxField::create('InheritBlockSets', _t('BlocksSiteTreeExtension.InheritBlocksFromBlockSets', 'Inherit Blocks from Block Sets')));
141
			}
142
		}
143
	}
144
145
	/**
146
	 * Called from templates to get rendered blocks for the given area.
147
	 *
148
	 * @param string $area
149
	 * @param int    $limit Limit the items to this number, or null for no limit
150
	 */
151
	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...
152
	{
153
		if ($this->owner->ID <= 0) {
154
			return;
155
		} // blocks break on fake pages ie Security/login
156
157
		$list = $this->getBlockList($area);
158
159
		foreach ($list as $block) {
160
			if (!$block->canView()) {
161
				$list->remove($block);
162
			}
163
		}
164
165
		if ($limit !== null) {
166
			$list = $list->limit($limit);
167
		}
168
169
		$data = array();
170
		$data['HasBlockArea'] = ($this->owner->canEdit() && isset($_REQUEST['block_preview']) && $_REQUEST['block_preview']) || $list->Count() > 0;
171
		$data['BlockArea'] = $list;
172
		$data['AreaID'] = $area;
173
174
		$data = $this->owner->customise($data);
175
176
		$template = array('BlockArea_'.$area);
177
178
		if (SSViewer::hasTemplate($template)) {
179
			return $data->renderWith($template);
180
		} else {
181
			return $data->renderWith('BlockArea');
182
		}
183
	}
184
185
	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...
186
	{
187
		if ($this->owner->canEdit() && isset($_REQUEST['block_preview']) && $_REQUEST['block_preview']) {
188
			return true;
189
		}
190
191
		$list = $this->getBlockList($area);
192
193
		foreach ($list as $block) {
194
			if (!$block->canView()) {
195
				$list->remove($block);
196
			}
197
		}
198
199
		return $list->Count() > 0;
200
	}
201
202
	/**
203
	 * Get a merged list of all blocks on this page and ones inherited from BlockSets.
204
	 *
205
	 * @param string|null $area            filter by block area
206
	 * @param bool        $includeDisabled Include blocks that have been explicitly excluded from this page
207
	 *                                     i.e. blocks from block sets added to the "disable inherited blocks" list
208
	 *
209
	 * @return ArrayList
210
	 * */
211
	public function getBlockList($area = null, $includeDisabled = false)
212
	{
213
		$includeSets = $this->blockManager->getUseBlockSets() && $this->owner->InheritBlockSets;
214
		$blocks = ArrayList::create();
215
216
		// get blocks directly linked to this page
217
		$nativeBlocks = $this->owner->Blocks()->sort('Sort');
218
		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...
219
			$nativeBlocks = $nativeBlocks->filter('BlockArea', $area);
220
		}
221
222
		if ($nativeBlocks->count()) {
223
			foreach ($nativeBlocks as $block) {
224
				$blocks->add($block);
225
			}
226
		}
227
228
		// get blocks from BlockSets
229
		if ($includeSets) {
230
			$blocksFromSets = $this->getBlocksFromAppliedBlockSets($area, $includeDisabled);
231
			if ($blocksFromSets->count()) {
232
				// merge set sources
233
				foreach ($blocksFromSets as $block) {
234
					if (!$blocks->find('ID', $block->ID)) {
235
						if ($block->AboveOrBelow == 'Above') {
236
							$blocks->unshift($block);
237
						} else {
238
							$blocks->push($block);
239
						}
240
					}
241
				}
242
			}
243
		}
244
245
		return $blocks;
246
	}
247
248
	/**
249
	 * Get Any BlockSets that apply to this page.
250
	 *
251
	 * @return ArrayList
252
	 * */
253
	public function getAppliedSets()
254
	{
255
		$list = ArrayList::create();
256
		if (!$this->owner->InheritBlockSets) {
257
			return $list;
258
		}
259
260
		$sets = BlockSet::get()->where("(PageTypesValue IS NULL) OR (PageTypesValue LIKE '%:\"{$this->owner->ClassName}%')");
261
		$ancestors = $this->owner->getAncestors()->column('ID');
262
263
		foreach ($sets as $set) {
264
			$restrictedToParerentIDs = $set->PageParents()->column('ID');
265
			if (count($restrictedToParerentIDs)) {
266
				// check whether the set should include selected parent, in which case check whether
267
				// it was in the restricted parents list. If it's not, or if include parentpage
268
				// wasn't selected, we check the ancestors of this page.
269
				if ($set->IncludePageParent && in_array($this->owner->ID, $restrictedToParerentIDs)) {
270
					$list->add($set);
271
				} else {
272
					if (count($ancestors)) {
273
						foreach ($ancestors as $ancestor) {
274
							if (in_array($ancestor, $restrictedToParerentIDs)) {
275
								$list->add($set);
276
								continue;
277
							}
278
						}
279
					}
280
				}
281
			} else {
282
				$list->add($set);
283
			}
284
		}
285
286
		return $list;
287
	}
288
289
	/**
290
	 * Get all Blocks from BlockSets that apply to this page.
291
	 *
292
	 * @return ArrayList
293
	 * */
294
	public function getBlocksFromAppliedBlockSets($area = null, $includeDisabled = false)
295
	{
296
		$blocks = ArrayList::create();
297
		$sets = $this->getAppliedSets();
298
299
		if (!$sets->count()) {
300
			return $blocks;
301
		}
302
303
		foreach ($sets as $set) {
304
			$setBlocks = $set->Blocks()->sort('Sort DESC');
305
306
			if (!$includeDisabled) {
307
				$setBlocks = $setBlocks->exclude('ID', $this->owner->DisabledBlocks()->column('ID'));
308
			}
309
310
			if ($area) {
311
				$setBlocks = $setBlocks->filter('BlockArea', $area);
312
			}
313
314
			$blocks->merge($setBlocks);
315
		}
316
317
		$blocks->removeDuplicates();
318
319
		return $blocks;
320
	}
321
322
	/**
323
	 * Get's the link for a block area preview button.
324
	 *
325
	 * @return string
326
	 * */
327
	public function areasPreviewLink()
328
	{
329
		return Controller::join_links($this->owner->Link(), '?block_preview=1');
330
	}
331
332
	/**
333
	 * Get's html for a block area preview button.
334
	 *
335
	 * @return string
336
	 * */
337
	public function areasPreviewButton()
338
	{
339
		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>';
340
	}
341
}
342