Completed
Push — master ( 9da255...e06f1c )
by Leo
03:13
created

Block::onBeforeWrite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
3
use SaltedHerring\Debugger as Debugger;
4
5
class Block extends DataObject {
6
	protected static $db = array (
7
		'SortOrder'			=>	'Int',
8
		'Title'				=>	'Varchar(64)',
9
		'TitleWrapper'		=>	'Enum("h2,h3,h4,h5,h6")',
10
		'hideTitle'			=>	'Boolean',
11
		'showBlockbyClass'	=>	'Boolean',
12
		'Description'		=>	'Varchar(128)',
13
		'MemberVisibility'	=>	'Varchar(255)',
14
		'shownInClass'		=>	'Text',
15
		'addMarginTop'		=>	'Boolean',
16
		'addMarginBottom'	=>	'Boolean'
17
	);
18
	
19
	protected static $many_many = array (
20
		'Pages'				=>	'Page'
21
	);
22
	
23
	protected static $default_sort = array(
24
		'SortOrder'			=>	'ASC',
25
		'ID'					=>	'DESC'
26
	);
27
		
28
	protected static $create_table_options = array(
29
		'MySQLDatabase'		=> 'ENGINE=MyISAM'
30
    );
31
	
32
	protected static $extensions = array (
33
		'StandardPermissions'
34
	);
35
	
36
	protected static $summary_fields = array(
37
		'BlockType',
38
		'Title', 
39
		'Description',
40
		'shownOn',
41
		'VisibleTo',
42
		'Published'
43
	);
44
	
45
	protected static $field_labels = array(
46
		'BlockType'			=>	'Block type',
47
		'shownOn'			=>	'is shown on',
48
		'VisibleTo'			=>	'Visible to'
49
	);
50
	
51
	public function VisibleTo() {
52
		if (strlen(trim($this->MemberVisibility)) > 0) {
53
			$lists = 'Group: ' . str_replace(',','<br />Group: ', $this->MemberVisibility);
54
		}else{
55
			$lists = '<em>&lt;All&gt;</em>';
56
		}
57
		
58
		return new LiteralField('VisibleTo',$lists);
59
	}
60
	
61
	public function BlockType() {
62
		return $this->singular_name();
63
	}
64
	
65
	public function shownOn() {
66
		if ($this->showBlockbyClass) {
67
			if (strlen(trim($this->shownInClass)) > 0) {
68
				$lists = 'Type: ' . str_replace(',','<br />Type: ', $this->shownInClass);
69
			}else{
70
				$lists = '<em>&lt;not assigned&gt;</em>';
71
			}
72
		}else{
73
			if ($this->Pages()->count() > 0) {
74
				$lists = 'Page: ' . implode('<br />Page: ', $this->Pages()->column('Title'));
75
			}else{
76
				$lists = '<em>&lt;not assigned&gt;</em>';
77
			}
78
		}
79
		return new LiteralField('shownOn',$lists);
80
	}
81
	
82
	public function getCMSFields() {
83
		$fields = parent::getCMSFields();
84
		$fields->removeFieldFromTab('Root', 'Pages');
85
		$fields->removeFieldsFromTab('Root.Main', array(
86
			'SortOrder',
87
			'showBlockbyClass',
88
			'shownInClass',
89
			'MemberVisibility'
90
		));
91
		
92
		$fields->addFieldToTab('Root.Main', LiteralField::create('Status', 'Status: ' . $this->Published()), 'Title');
93
		
94
		$memberGroups = Group::get();
95
		$sourcemap = $memberGroups->map('Code', 'Title');
96
		$source = array(
97
			'anonymous'		=>	'Anonymous visitors'
98
		);
99
		foreach ($sourcemap as $mapping => $key) {
100
			$source[$mapping] = $key;
101
		}
102
		
103
		$memberVisibility = new CheckboxSetField(
104
			$name = "MemberVisibility",
105
			$title = "Show block for specific groups",
106
			$source
107
		);
108
		
109
		$memberVisibility->setDescription('Show this block only for the selected group(s). If you select no groups, the block will be visible to all members.');
110
		
111
		$availabelClasses = $this->availableClasses();
112
		$inClass = new CheckboxSetField(
113
			$name = "shownInClass",
114
			$title = "Show block for specific content types",
115
			$availabelClasses
116
		);
117
		
118
		$filterSelector = OptionsetField::create(
119
			'showBlockbyClass',
120
			'Choose filter set',
121
			array(
122
				'0'			=>	'by page',
123
				'1'			=>	'by page/data type'
124
			)
125
		)->setDescription('<p><br /><strong>by page</strong>: block will be displayed in the selected page(s)<br /><strong>by page/data type</strong>: block will be displayed on the pages created with the particular page/data type. e.g. is <strong>"InternalPage"</strong> is picked, the block will be displayed, and will ONLY be displayed on all <strong>Internal Pages</strong></p>');
126
		
127
		$availablePages = Page::get()->exclude('ClassName', array(
128
			'ErrorPage',
129
			'RedirectorPage',
130
			'VirtualPage'
131
		));
132
		$pageSelector = new CheckboxSetField(
133
			$name = "Pages",
134
			$title = "Show on Page(s)",
135
			$availablePages->map('ID','Title')
136
		);
137
		
138
		
139
		if ($this->canConfigPageAndType(Member::currentUser())) {
140
			$fields->addFieldsToTab('Root.VisibilitySettings', array(
141
				$filterSelector,
142
				$pageSelector,
143
				$inClass
144
			));
145
		}
146
		
147
		if ($this->canConfigMemberVisibility(Member::currentUser())) {
148
			$fields->addFieldToTab('Root.VisibilitySettings', $memberVisibility);
149
		}
150
		
151
		if (!$fields->fieldByName('Options')) {
152
			$fields->insertBefore($right = RightSidebar::create('Options'), 'Root');
0 ignored issues
show
Documentation introduced by
'Root' is of type string, but the function expects a object<FormField>.

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...
153
	    }
154
	
155
	    $fields->addFieldsToTab('Options', array(
156
			CheckboxField::create('addMarginTop', 'add "margin-top" class to block wrapper'),
157
			CheckboxField::create('addMarginBottom', 'add "margin-bottom" class to block wrapper')
158
	    ));
159
160
		return $fields;
161
	}
162
	
163
	public function doPublish() {
164
		$this->writeToStage('Live');
0 ignored issues
show
Documentation Bug introduced by
The method writeToStage does not exist on object<Block>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
165
	}
166
	
167
	public function onBeforeWrite() {
168
		parent::onBeforeWrite();
169
		if (empty($this->byPass)) {
0 ignored issues
show
Documentation introduced by
The property byPass does not exist on object<Block>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
170
			$this->readmode = Versioned::get_reading_mode();
0 ignored issues
show
Documentation introduced by
The property readmode does not exist on object<Block>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
171
			Versioned::set_reading_mode('Stage.Stage');
172
		}
173
	}
174
	
175
	public function onAfterWrite() {
176
		parent::onAfterWrite();
177
		if (isset($this->readmode)) {
178
			Versioned::set_reading_mode('Stage.' . $this->readmode);
0 ignored issues
show
Documentation introduced by
The property readmode does not exist on object<Block>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
179
		}
180
	}
181
	
182
	public function availableClasses() {
183
		$Classes = array_diff(
184
			ClassInfo::subclassesFor('Page'),
185
			ClassInfo::subclassesFor('RedirectorPage'),
186
			ClassInfo::subclassesFor('VirtualPage')
187
		);
188
		return $Classes;
189
	}
190
	
191
	public function forTemplate() {
192
		if ($this->canDisplayMemberCheck()) {
193
			return $this->renderWith(array($this->getClassName(), 'BaseBlock'));
194
		}
195
		
196
		return false;
197
	}
198
	
199
	public function canDisplayMemberCheck() {
200
		$rawVisibility = $this->MemberVisibility;
201
		
202
		if (empty($rawVisibility)) {
203
			return true;
204
		}
205
		
206
		$visibility = explode(',', $rawVisibility);
207
		$member = Member::currentUser();
208
		
209
		if (!$member && in_array('anonymous', $visibility)) {
210
			return true;
211
		}
212
		
213
		if ($member) {
214
			$memberGroups = $member->Groups()->column('Code');
215
			foreach ($memberGroups as $memberGroup) {
216
				if (in_array($memberGroup, $visibility)) {
217
					return true;
218
				}
219
			}
220
		}
221
		
222
		return false;
223
	}
224
	
225
	public function frontendEditable() {
226
		$member = Member::currentUser();		
227
		return $this->canEdit($member);
228
	}
229
	
230
	public function Type2Class() {
231
		return strtolower(str_replace(' ', '-', $this->singular_name()));
232
	}
233
	
234
	/*public function doPublish() {
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
235
		$this->writeToStage('Live');
236
	}*/
237
	
238
	public function Published() {
239
		return $this->isPublished() ? 'Yes' : 'No';
240
	}
241
	
242
	public function isPublished() {
243
		if (!empty(Versioned::get_by_stage('Block', 'Live')->byID($this->ID))) {
244
			return true;
245
		}
246
		
247
		return false;
248
	}
249
250
}