Completed
Push — master ( ae8931...2d50a9 )
by Leo
02:38
created

SHBlockinPage::dockedBlocks()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 3
eloc 11
nc 3
nop 0
1
<?php
2
class SHBlockinPage extends Extension {
3
	protected static $belongs_many_many = array (
4
		'SHBlocks'			=>	'SHBlock'
5
	);
6
	
7
	public function updateCMSFields( FieldList $fields ) {
8
		$ancestry = ClassInfo::ancestry($this->owner->ClassName);
9
		if (!in_array('RedirectorPage', $ancestry) && !in_array('VirtualPage', $ancestry)) {
10
			$blocks = $this->owner->SHBlocks();
11
			$blocks_grid = $this->gridBuilder('SHBlocks', $blocks, '', true,'GridFieldConfig_RelationEditor');
12
			$docked_grid = $this->gridBuilder('DockedBlocks', $this->dockedBlocks(), '');
13
			
14
			$fields->addFieldToTab('Root.MyBlocks', $blocks_grid);
15
			$fields->addFieldToTab('Root.DockedBlocks', $docked_grid);
16
		}
17
	}
18
	
19
	private function gridBuilder($name, $source, $label = '', $canAdd = false, $gridHeaderType = 'GridFieldConfig_RecordEditor') {
20
		/*
21
		GridFieldConfig_Base
22
		GridFieldConfig_RecordViewer
23
		GridFieldConfig_RecordEditor
24
		GridFieldConfig_RelationEditor
25
		*/
26
		if ($label == '') { $label = $name; }
27
		$grid = new GridField($name, $label, $source);
28
		$config = $gridHeaderType::create();
29
		$config->removeComponentsByType('GridFieldAddNewButton');
30
		if ( $canAdd ) {
31
			$config->addComponents(
32
				$multiClass = new MultiClassSelector(),
33
				$sortable = new GridFieldOrderableRows('SortOrder')
34
			);
35
			$subBlocks = ClassInfo::subclassesFor('SHBlock');
36
			if (is_null($subBlocks)) {
37
				$subBlocks = array('SHBlock');
38
			}else{
39
				unset($subBlocks['SHBlock']);
40
				
41
				foreach ($subBlocks as $key => &$value) {
42
					$value = empty($key::$singular_name) ? ucwords(trim(strtolower(preg_replace('/_?([A-Z])/', ' $1', $value)))) : $key::$singular_name;
43
				}
44
			}
45
			$multiClass->setClasses($subBlocks);
46
		}
47
		$grid->setConfig($config);
48
		return $grid;
49
	}
50
		
51
	private function dockedBlocks() {
52
		$blocks = SHBlock::get();
53
		$IDs = array();
54
		$ClassName = $this->owner->ClassName;
55
		$Classes = $blocks->map('ID', 'shownInClass');
56
		foreach ($Classes as $BlockID => $Class) {
57
			$listedClasses = explode(',', $Class);
58
			if (in_array($ClassName, $listedClasses)) {
59
				$IDs[] = $BlockID;
60
			}
61
		}
62
		$blocks = SHBlock::get()->filter('ID', $IDs)->sort('SortOrder','ASC');
63
		return $blocks;
64
	}
65
}