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 ( bea034...4abf00 )
by Shea
02:05
created

Block::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 0 Features 1
Metric Value
c 9
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
/**
3
 * Block
4
 * Subclass this basic Block with your more interesting ones.
5
 *
6
 * @author Shea Dawson <[email protected]>
7
 */
8
class Block extends DataObject implements PermissionProvider
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...
9
{
10
    /**
11
     * @var array
12
     */
13
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
14
        'Title' => 'Varchar(255)',
15
        'CanViewType' => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')",
16
        'ExtraCSSClasses' => 'Varchar',
17
        // these are legacy fields, in place to make migrations from old blocks version easier
18
        'Weight' => 'Int',
19
        'Area' => 'Varchar',
20
        'Published' => 'Boolean',
21
    );
22
23
    /**
24
     * @var array
25
     */
26
    private static $many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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...
27
        'ViewerGroups' => 'Group',
28
    );
29
30
    /**
31
     * @var array
32
     */
33
    private static $belongs_many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $belongs_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
        'Pages' => 'SiteTree',
35
        'BlockSets' => 'BlockSet',
36
    );
37
38
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields 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...
39
        'singular_name',
40
        'Title',
41
        'isPublishedField',
42
        'UsageListAsString',
43
    );
44
45
    private static $searchable_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $searchable_fields 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...
46
            'Title',
47
            'ClassName',
48
    );
49
50
    public function fieldLabels($includerelations = true)
51
    {
52
        $labels =  parent::fieldLabels($includerelations);
53
54
        $labels = array_merge($labels, array(
55
            'singular_name' => _t('Block.BlockType', 'Block Type'),
56
            'Title' => _t('Block.Title', 'Title'),
57
            'isPublishedField' => _t('Block.IsPublishedField', 'Published'),
58
            'UsageListAsString' => _t('Block.UsageListAsString', 'Used on'),
59
            'ExtraCSSClasses' => _t('Block.ExtraCSSClasses', 'Extra CSS Classes'),
60
            'Content' => _t('Block.Content', 'Content'),
61
            'ClassName' => _t('Block.BlockType', 'Block Type'),
62
        ));
63
64
        return $labels;
65
    }
66
67
    public function getDefaultSearchContext()
68
    {
69
        $context = parent::getDefaultSearchContext();
70
71
        $results = $this->blockManager->getBlockClasses();
72
        if (sizeof($results) > 1) {
73
            $classfield = new DropdownField('ClassName', _t('Block.BlockType', 'Block Type'));
74
            $classfield->setSource($results);
75
            $classfield->setEmptyString(_t('Block.Any', '(any)'));
76
            $context->addField($classfield);
77
        }
78
79
        return $context;
80
    }
81
82
    /**
83
     * @var array
84
     */
85
    private static $default_sort = array('Title' => 'ASC');
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $default_sort 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...
86
87
    /**
88
     * @var array
89
     */
90
    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...
91
        'blockManager' => '%$blockManager',
92
    );
93
94
    /**
95
     * @var BlockManager
96
     */
97
    public $blockManager;
98
99
    /**
100
     * @var BlockController
101
     */
102
    protected $controller;
103
104
    /**
105
     * @return mixed
106
     */
107
    public function getTypeForGridfield()
108
    {
109
        return $this->singular_name();
110
    }
111
112
    public function getCMSFields()
113
    {
114
        Requirements::add_i18n_javascript(BLOCKS_DIR.'/javascript/lang');
115
116
        // this line is a temporary patch until I can work out why this dependency isn't being
117
        // loaded in some cases...
118
        if (!$this->blockManager) {
119
            $this->blockManager = singleton('BlockManager');
120
        }
121
122
        $fields = parent::getCMSFields();
123
124
        // ClassNmae - block type/class field
125
        $classes = $this->blockManager->getBlockClasses();
126
        $fields->addFieldToTab('Root.Main', DropdownField::create('ClassName', _t('Block.BlockType', 'Block Type'), $classes)->addExtraClass('block-type'), 'Title');
127
128
        // BlockArea - display areas field if on page edit controller
129
        if (Controller::curr()->class == 'CMSPageEditController') {
130
            $currentPage = Controller::curr()->currentPage();
131
            $fields->addFieldToTab(
132
                'Root.Main',
133
                $blockAreaField = DropdownField::create('ManyMany[BlockArea]', _t('Block.BlockArea','Block Area'), $this->blockManager->getAreasForPageType($currentPage->ClassName))
134
                    ->setHasEmptyDefault(true)
135
                    ->setEmptyString('(Select one)'),
136
                'ClassName'
137
            );
138
            if (BlockManager::config()->get('block_area_preview')) {
139
                $blockAreaField->setRightTitle($currentPage->areasPreviewButton());
140
            }
141
        }
142
143
        $fields->removeFieldFromTab('Root', 'BlockSets');
144
        $fields->removeFieldFromTab('Root', 'Pages');
145
146
        // legacy fields, will be removed in later release
147
        $fields->removeByName('Weight');
148
        $fields->removeByName('Area');
149
        $fields->removeByName('Published');
150
151
        if ($this->blockManager->getUseExtraCSSClasses()) {
152
            $fields->addFieldToTab('Root.Main', $fields->dataFieldByName('ExtraCSSClasses'), 'Title');
153
        } else {
154
            $fields->removeByName('ExtraCSSClasses');
155
        }
156
157
        // Viewer groups
158
        $fields->removeFieldFromTab('Root', 'ViewerGroups');
159
        $groupsMap = Group::get()->map('ID', 'Breadcrumbs')->toArray();
160
        asort($groupsMap);
161
        $viewersOptionsField = new OptionsetField(
162
            'CanViewType',
163
            _t('SiteTree.ACCESSHEADER', 'Who can view this page?')
164
        );
165
        $viewerGroupsField = ListboxField::create('ViewerGroups', _t('SiteTree.VIEWERGROUPS', 'Viewer Groups'))
166
            ->setMultiple(true)
167
            ->setSource($groupsMap)
168
            ->setAttribute(
169
                'data-placeholder',
170
                _t('SiteTree.GroupPlaceholder', 'Click to select group')
171
        );
172
        $viewersOptionsSource = array();
173
        $viewersOptionsSource['Anyone'] = _t('SiteTree.ACCESSANYONE', 'Anyone');
174
        $viewersOptionsSource['LoggedInUsers'] = _t('SiteTree.ACCESSLOGGEDIN', 'Logged-in users');
175
        $viewersOptionsSource['OnlyTheseUsers'] = _t('SiteTree.ACCESSONLYTHESE', 'Only these people (choose from list)');
176
        $viewersOptionsField->setSource($viewersOptionsSource)->setValue('Anyone');
177
178
        $fields->addFieldToTab('Root', new Tab('ViewerGroups', _t('Block.ViewerGroups', 'Viewer Groups')));
179
        $fields->addFieldsToTab('Root.ViewerGroups', array(
180
            $viewersOptionsField,
181
            $viewerGroupsField,
182
        ));
183
184
        // Disabled for now, until we can list ALL pages this block is applied to (inc via sets)
185
        // As otherwise it could be misleading
186
        // Show a GridField (list only) with pages which this block is used on
187
        // $fields->removeFieldFromTab('Root.Pages', 'Pages');
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
188
        // $fields->addFieldsToTab('Root.Pages',
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
189
        // 		new GridField(
190
        // 				'Pages',
191
        // 				'Used on pages',
192
        // 				$this->Pages(),
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
193
        // 				$gconf = GridFieldConfig_Base::create()));
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
194
        // enhance gridfield with edit links to pages if GFEditSiteTreeItemButtons is available
195
        // a GFRecordEditor (default) combined with BetterButtons already gives the possibility to
196
        // edit versioned records (Pages), but STbutton loads them in their own interface instead
197
        // of GFdetailform
198
        // if(class_exists('GridFieldEditSiteTreeItemButton')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
199
        // 	$gconf->addComponent(new GridFieldEditSiteTreeItemButton());
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...
200
        // }
201
202
        return $fields;
203
    }
204
205
    /**
206
     * Renders this block with appropriate templates
207
     * looks for templates that match BlockClassName_AreaName
208
     * falls back to BlockClassName.
209
     *
210
     * @return string
211
     **/
212
    public function forTemplate()
213
    {
214
        if ($this->BlockArea) {
0 ignored issues
show
Documentation introduced by
The property BlockArea 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...
215
            $template = array($this->class.'_'.$this->BlockArea);
0 ignored issues
show
Documentation introduced by
The property BlockArea 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...
216
217
            if (SSViewer::hasTemplate($template)) {
218
                return $this->renderWith($template);
219
            }
220
        }
221
222
        return $this->renderWith($this->ClassName, $this->getController());
223
    }
224
225
    /**
226
     * @return string
227
     */
228
    public function BlockHTML()
229
    {
230
        return $this->forTemplate();
231
    }
232
233
    /*
234
     * Checks if deletion was an actual deletion, not just unpublish
235
     * If so, remove relations
236
     */
237
    public function onAfterDelete()
238
    {
239
        parent::onAfterDelete();
240
        if (Versioned::current_stage() == 'Stage') {
241
            $this->Pages()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method Pages 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...
242
            $this->BlockSets()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method BlockSets 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...
243
        }
244
    }
245
246
    /**
247
     * Remove relations onAfterDuplicate.
248
     */
249
    public function onAfterDuplicate()
250
    {
251
        // remove relations to pages & blocksets duplicated from the original item
252
        $this->Pages()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method Pages 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...
253
        $this->BlockSets()->removeAll();
0 ignored issues
show
Documentation Bug introduced by
The method BlockSets 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...
254
    }
255
256
    /*
257
     * Base permissions
258
     */
259
    public function canView($member = null)
260
    {
261
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
262
            $member = Member::currentUserID();
263
        }
264
265
        // admin override
266
        if ($member && Permission::checkMember($member, array('ADMIN', 'SITETREE_VIEW_ALL'))) {
267
            return true;
268
        }
269
270
        // Standard mechanism for accepting permission changes from extensions
271
        $extended = $this->extendedCan('canView', $member);
272
        if ($extended !== null) {
273
            return $extended;
274
        }
275
276
        // check for empty spec
277
        if (!$this->CanViewType || $this->CanViewType == 'Anyone') {
0 ignored issues
show
Documentation introduced by
The property CanViewType 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...
278
            return true;
279
        }
280
281
        // check for any logged-in users
282
        if ($this->CanViewType == 'LoggedInUsers' && $member) {
0 ignored issues
show
Documentation introduced by
The property CanViewType 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...
283
            return true;
284
        }
285
286
        // check for specific groups
287
        if ($member && is_numeric($member)) {
288
            $member = DataObject::get_by_id('Member', $member);
289
        }
290
        if ($this->CanViewType == 'OnlyTheseUsers' && $member && $member->inGroups($this->ViewerGroups())) {
0 ignored issues
show
Documentation introduced by
The property CanViewType 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...
Documentation Bug introduced by
The method ViewerGroups 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...
291
            return true;
292
        }
293
294
        return false;
295
    }
296
297
    public function canEdit($member = null)
298
    {
299
        return Permission::check('ADMIN') || Permission::check('BLOCK_EDIT');
300
    }
301
302
    public function canDelete($member = null)
303
    {
304
        return Permission::check('ADMIN') || Permission::check('BLOCK_DELETE');
305
    }
306
307
    public function canCreate($member = null)
308
    {
309
        return Permission::check('ADMIN') || Permission::check('BLOCK_CREATE');
310
    }
311
312
    public function canPublish($member = null)
0 ignored issues
show
Unused Code introduced by
The parameter $member is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
313
    {
314
        return Permission::check('ADMIN') || Permission::check('BLOCK_PUBLISH');
315
    }
316
317
    public function providePermissions()
318
    {
319
        return array(
320
            'BLOCK_EDIT' => array(
321
                'name' => _t('Block.EditBlock', 'Edit a Block'),
322
                'category' => _t('Block.PermissionCategory', 'Blocks'),
323
            ),
324
            'BLOCK_DELETE' => array(
325
                'name' => _t('Block.DeleteBlock', 'Delete a Block'),
326
                'category' => _t('Block.PermissionCategory', 'Blocks'),
327
            ),
328
            'BLOCK_CREATE' => array(
329
                'name' => _t('Block.CreateBlock', 'Create a Block'),
330
                'category' => _t('Block.PermissionCategory', 'Blocks'),
331
            ),
332
            'BLOCK_PUBLISH' => array(
333
                'name' => _t('Block.PublishBlock', 'Publish a Block'),
334
                'category' => _t('Block.PermissionCategory', 'Blocks'),
335
            ),
336
        );
337
    }
338
339
    public function onAfterWrite()
340
    {
341
        parent::onAfterWrite();
342
        if ($this->hasExtension('FilesystemPublisher')) {
343
            $this->republish($this);
0 ignored issues
show
Documentation Bug introduced by
The method republish 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...
344
        }
345
    }
346
347
    /**
348
     * Get a list of URL's to republish when this block changes
349
     * if using StaticPublisher module.
350
     */
351
    public function pagesAffectedByChanges()
352
    {
353
        $pages = $this->Pages();
0 ignored issues
show
Documentation Bug introduced by
The method Pages 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...
354
        $urls = array();
355
        foreach ($pages as $page) {
356
            $urls[] = $page->Link();
357
        }
358
359
        return $urls;
360
    }
361
362
    /*
363
     * Get a list of Page and Blockset titles this block is used on
364
     */
365
    public function UsageListAsString()
366
    {
367
        $pages = implode(', ', $this->Pages()->column('URLSegment'));
0 ignored issues
show
Documentation Bug introduced by
The method Pages 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...
368
        $sets = implode(', ', $this->BlockSets()->column('Title'));
0 ignored issues
show
Documentation Bug introduced by
The method BlockSets 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...
369
        $_t_pages = _t('Block.PagesAsString', 'Pages: {pages}', '', array('pages' => $pages));
0 ignored issues
show
Documentation introduced by
array('pages' => $pages) is of type array<string,string,{"pages":"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...
370
        $_t_sets = _t('Block.BlockSetsAsString', 'Block Sets: {sets}', '', array('sets' => $sets));
0 ignored issues
show
Documentation introduced by
array('sets' => $sets) is of type array<string,string,{"sets":"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...
371
        if ($pages && $sets) {
372
            return "$_t_pages<br />$_t_sets";
373
        }
374
        if ($pages) {
375
            return $_t_pages;
376
        }
377
        if ($sets) {
378
            return $_t_sets;
379
        }
380
    }
381
382
    /**
383
     * Check if this block has been published.
384
     *
385
     * @return bool True if this page has been published.
386
     */
387
    public function isPublished()
388
    {
389
        if (!$this->exists()) {
390
            return false;
391
        }
392
393
        return (DB::query("SELECT \"ID\" FROM \"Block_Live\" WHERE \"ID\" = $this->ID")->value())
394
            ? 1
395
            : 0;
396
    }
397
398
    /**
399
     * Check if this block has been published.
400
     *
401
     * @return bool True if this page has been published.
402
     */
403
    public function isPublishedNice()
404
    {
405
        $field = Boolean::create('isPublished');
406
        $field->setValue($this->isPublished());
407
408
        return $field->Nice();
409
    }
410
411
    /**
412
     * @return HTMLText
413
     */
414
    public function isPublishedIcon()
415
    {
416
        $obj = HTMLText::create();
417
        if ($this->isPublished()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->isPublished() of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. 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 integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
418
            $obj->setValue('<img src="/framework/admin/images/alert-good.gif" />');
419
        } else {
420
            $obj->setValue('<img src="/framework/admin/images/alert-bad.gif" />');
421
        }
422
        return $obj;
423
    }
424
425
    /**
426
     * CSS Classes to apply to block element in template.
427
     *
428
     * @return string $classes
429
     */
430
    public function CSSClasses($stopAtClass = 'DataObject')
431
    {
432
        $classes = strtolower(parent::CSSClasses($stopAtClass));
433
434
        if (!empty($classes) && ($prefix = $this->blockManager->getPrefixDefaultCSSClasses())) {
435
            $classes = $prefix.str_replace(' ', " {$prefix}", $classes);
436
        }
437
438
        if ($this->blockManager->getUseExtraCSSClasses()) {
439
            $classes = $this->ExtraCSSClasses ? $classes." $this->ExtraCSSClasses" : $classes;
0 ignored issues
show
Documentation introduced by
The property ExtraCSSClasses 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...
440
        }
441
442
        return $classes;
443
    }
444
445
    /**
446
     * Access current page scope from Block templates with $CurrentPage
447
     *
448
     * @return Controller
449
     */
450
    public function getCurrentPage()
451
    {
452
        return Controller::curr();
453
    }
454
455
    /**
456
     * @throws Exception
457
     *
458
     * @return BlockController
459
     */
460
    public function getController()
461
    {
462
        if ($this->controller) {
463
            return $this->controller;
464
        }
465
        foreach (array_reverse(ClassInfo::ancestry($this->class)) as $blockClass) {
466
            $controllerClass = "{$blockClass}_Controller";
467
            if (class_exists($controllerClass)) {
468
                break;
469
            }
470
        }
471
        if (!class_exists($controllerClass)) {
0 ignored issues
show
Bug introduced by
The variable $controllerClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
472
            throw new Exception("Could not find controller class for $this->classname");
0 ignored issues
show
Bug introduced by
The property classname does not seem to exist. Did you mean ClassName?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
473
        }
474
        $this->controller = Injector::inst()->create($controllerClass, $this);
475
        $this->controller->init();
476
477
        return $this->controller;
478
    }
479
}
480