Completed
Pull Request — master (#71)
by John
02:15
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($autocompleter = 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
                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...
69
                    $autocompleter->setSearchList(
70
                        BaseElement::get()->filter('ClassName', array_keys($list))
71
                    );
72
                }
73
74
                $widgetArea = new GridField(
75
                    'Elements',
76
                    Config::inst()->get("ElementPageExtension", 'elements_title'),
77
                    $elements,
78
                    $config
79
                );
80
81
                $fields->addFieldToTab('Root.Main', $widgetArea);
82
            } else {
83
                $fields->addFieldToTab('Root.Main', LiteralField::create('warn', '<p class="message notice">Once you save this object you will be able to add items</p>'));
84
            }
85
        });
86
87
        return parent::getCMSFields();
88
    }
89
90
    /**
91
     * @return array
92
     */
93
    public function getAvailableTypes() {
94
        if (is_array($this->config()->get('allowed_elements'))) {
95
            $list = $this->config()->get('allowed_elements');
96
97 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...
98
                $sorted = array();
99
100
                foreach ($list as $class) {
101
                    $inst = singleton($class);
102
103
                    if ($inst->canCreate()) {
104
                        $sorted[$class] = singleton($class)->i18n_singular_name();
105
                    }
106
                }
107
108
                $list = $sorted;
109
                asort($list);
110
            }
111 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...
112
            $classes = ClassInfo::subclassesFor('BaseElement');
113
            $list = array();
114
            unset($classes['BaseElement']);
115
116
            $disallowedElements = (array) $this->config()->get('disallowed_elements');
117
118
            if (!in_array('ElementVirtualLinked', $disallowedElements)) {
119
                array_push($disallowedElements, 'ElementVirtualLinked');
120
            }
121
122
            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...
123
                $inst = singleton($class);
124
125
                if (!in_array($class, $disallowedElements) && $inst->canCreate()) {
126
                    $list[$class] = singleton($class)->i18n_singular_name();
127
                }
128
            }
129
130
            asort($list);
131
        }
132
133
        if (method_exists($this, 'sortElementalOptions')) {
134
            $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...
135
        }
136
137
        return $list;
138
    }
139
140
    /**
141
     * Used in template instead of {@link Widgets()} to wrap each widget in its
142
     * controller, making it easier to access and process form logic and
143
     * actions stored in {@link WidgetController}.
144
     *
145
     * @return SS_List - Collection of {@link WidgetController} instances.
146
     */
147
    public function WidgetControllers() {
148
        $controllers = new ArrayList();
149
150
        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...
151
            $controller = $widget->getController();
152
153
            $controller->init();
154
            $controllers->push($controller);
155
        }
156
157
        return $controllers;
158
    }
159
}
160