Completed
Pull Request — master (#71)
by John
02:22
created

ElementList::WidgetControllers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
/**
4
 * A list contains nested {@link BaseElement} such as a list of related files.
5
 *
6
 * @package elemental
7
 */
8
class ElementList extends BaseElement
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
    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...
12
        'ListDescription' => 'HTMLText'
13
    );
14
15
    private static $has_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 $has_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...
16
        'Elements' => 'BaseElement'
17
    );
18
19
    private static $duplicate_relations = array(
0 ignored issues
show
Unused Code introduced by
The property $duplicate_relations 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...
20
        'Elements'
21
    );
22
23
    private static $title = "Element List Element";
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 $title 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...
24
25
    private static $description = "Orderable list of elements";
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 $description 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
27
    private static $enable_title_in_template = true;
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 $enable_title_in_template 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...
28
29
    /**
30
     * @return FieldList
31
     */
32
    public function getCMSFields()
33
    {
34
        $elements = $this->Elements();
0 ignored issues
show
Bug introduced by
The method Elements() does not exist on ElementList. Did you maybe mean all_allowed_elements()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
35
        $isInDb = $this->isInDB();
36
37
        $this->beforeUpdateCMSFields(function ($fields) use ($elements, $isInDb) {
38
            $fields->removeByName('Root.Elements');
39
            $fields->removeByName('Elements');
40
41
            $desc = HTMLEditorField::create('ListDescription', 'List Description');
42
            $desc->setRightTitle('Optional');
43
            $fields->addFieldToTab('Root.Main', $desc);
44
45
            if ($isInDb) {
46
                $adder = new ElementalGridFieldAddNewMultiClass('buttons-before-left');
47
48
                $list = $this->getAvailableTypes();
49
50
                if($list) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
51
                    $adder->setClasses($list);
52
                }
53
54
                $config = GridFieldConfig_RecordEditor::create(100);
55
                $config->addComponent(new GridFieldSortableRows('Sort'));
56
                $config->removeComponentsByType('GridFieldAddNewButton');
57
                $config->removeComponentsByType('GridFieldSortableHeader');
58
                $config->removeComponentsByType('GridFieldDeleteAction');
59
                $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
60
                $config->addComponent(new GridFieldTitleHeader());
61
                $config->addComponent($adder);
62
                $config->addComponent($autocomplete = new ElementalGridFieldAddExistingAutocompleter('buttons-before-right'));
63
64
                if ($this->owner->canDelete()) {
0 ignored issues
show
Documentation introduced by
The property owner does not exist on object<ElementList>. 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...
65
                    $config->addComponent(new ElementalGridFieldDeleteAction());
66
                }
67
68
                $searchList = BaseElement::get()->filter('AvailableGlobally', true);
69
                if($list) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
70
                    $searchList = $searchList->filter('ClassName', array_keys($list));
71
                }
72
                $autocomplete->setSearchList($searchList);
73
74
                $autocomplete->setResultsFormat('($ID) $Title');
75
                $autocomplete->setSearchFields(array('ID', 'Title'));
76
77
                $widgetArea = new GridField(
78
                    'Elements',
79
                    Config::inst()->get("ElementPageExtension", 'elements_title'),
80
                    $elements,
81
                    $config
82
                );
83
84
                $fields->addFieldToTab('Root.Main', $widgetArea);
85
            } else {
86
                $fields->addFieldToTab('Root.Main', LiteralField::create('warn', '<p class="message notice">Once you save this object you will be able to add items</p>'));
87
            }
88
        });
89
90
        return parent::getCMSFields();
91
    }
92
93
    /**
94
     * @return array
95
     */
96
    public function getAvailableTypes() {
97
        if (is_array($this->config()->get('allowed_elements'))) {
98
            $list = $this->config()->get('allowed_elements');
99
100 View Code Duplication
            if($this->config()->get('sort_types_alphabetically') !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
                $sorted = array();
102
103
                foreach ($list as $class) {
104
                    $inst = singleton($class);
105
106
                    if ($inst->canCreate()) {
107
                        $sorted[$class] = singleton($class)->i18n_singular_name();
108
                    }
109
                }
110
111
                $list = $sorted;
112
                asort($list);
113
            }
114 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
            $classes = ClassInfo::subclassesFor('BaseElement');
116
            $list = array();
117
            unset($classes['BaseElement']);
118
119
            $disallowedElements = (array) $this->config()->get('disallowed_elements');
120
121
            if (!in_array('ElementVirtualLinked', $disallowedElements)) {
122
                array_push($disallowedElements, 'ElementVirtualLinked');
123
            }
124
125
            foreach ($classes as $class) {
0 ignored issues
show
Bug introduced by
The expression $classes of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
126
                $inst = singleton($class);
127
128
                if (!in_array($class, $disallowedElements) && $inst->canCreate()) {
129
                    $list[$class] = singleton($class)->i18n_singular_name();
130
                }
131
            }
132
133
            asort($list);
134
        }
135
136
        if (method_exists($this, 'sortElementalOptions')) {
137
            $this->sortElementalOptions($list);
0 ignored issues
show
Documentation Bug introduced by
The method sortElementalOptions does not exist on object<ElementList>? 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...
138
        }
139
140
        return $list;
141
    }
142
143
    /**
144
     * Used in template instead of {@link Widgets()} to wrap each widget in its
145
     * controller, making it easier to access and process form logic and
146
     * actions stored in {@link WidgetController}.
147
     *
148
     * @return SS_List - Collection of {@link WidgetController} instances.
149
     */
150
    public function WidgetControllers() {
151
        $controllers = new ArrayList();
152
153
        foreach($this->Elements()->filter('Enabled', 1) as $widget) {
0 ignored issues
show
Bug introduced by
The method Elements() does not exist on ElementList. Did you maybe mean all_allowed_elements()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
154
            $controller = $widget->getController();
155
156
            $controller->init();
157
            $controllers->push($controller);
158
        }
159
160
        return $controllers;
161
    }
162
}
163