Notification::getCMSFields()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 34
c 2
b 0
f 1
dl 0
loc 59
rs 9.376
cc 3
nc 1
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace ilateral\SilverStripe\Notifier\Model;
4
5
use SilverStripe\Core\ClassInfo;
6
use SilverStripe\ORM\DataObject;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\ORM\HasManyList;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Forms\GridField\GridField;
11
use ilateral\SilverStripe\Notifier\Notifier;
12
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
13
use ilateral\SilverStripe\Notifier\Types\NotificationType;
14
use LogicException;
15
use SilverStripe\Core\Config\Config;
16
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
17
use Symbiote\GridFieldExtensions\GridFieldAddNewMultiClass;
18
19
/**
20
 * @property string BaseClassName
21
 * @property bool StateCreated
22
 * @property bool StateUpdated
23
 * @property bool StateDeleted
24
 * @property string NotificationName
25
 * @property string ObjectType
26
 *
27
 * @method HasManyList Rules
28
 * @method HasManyList Types
29
 */
30
class Notification extends DataObject
31
{
32
    const STATE_CREATED = 'StateCreated';
33
34
    const STATE_UPDATED = 'StateUpdated';
35
36
    const STATE_DELETED = 'StateDeleted';
37
38
    private static $table_name = 'Notifications_Notification';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
39
40
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
41
        'BaseClassName' => 'Varchar',
42
        'StateCreated' => 'Boolean',
43
        'StateUpdated' => 'Boolean',
44
        'StateDeleted' => 'Boolean'
45
    ];
46
47
    private static $has_many = [
0 ignored issues
show
introduced by
The private property $has_many is not used, and could be removed.
Loading history...
48
        'Rules' => NotificationRule::class,
49
        'Types' => NotificationType::class
50
    ];
51
52
    private static $cascade_deletes = [
0 ignored issues
show
introduced by
The private property $cascade_deletes is not used, and could be removed.
Loading history...
53
        'Rules',
54
        'Types'
55
    ];
56
57
    private static $casting = [
0 ignored issues
show
introduced by
The private property $casting is not used, and could be removed.
Loading history...
58
        'NotificationName' => 'Varchar',
59
        'ObjectType' => 'Varchar',
60
        'Summary' => 'Varchar'
61
    ];
62
63
    private static $field_labels = [
0 ignored issues
show
introduced by
The private property $field_labels is not used, and could be removed.
Loading history...
64
        'NotificationName' => 'Notification',
65
        'ObjectType' => 'Object to monitor',
66
        'BaseClassName' => 'Object to Monitor',
67
        'StateCreated' => 'Notify when created',
68
        'StateUpdated' => 'Notify on any update',
69
        'StateDeleted' => 'Notify when deleted',
70
        'Rules' => 'Modification Rules',
71
        'Rules.Count' => '# of Rules',
72
        'Types' => 'Notification Types'
73
    ];
74
75
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
76
        'NotificationName',
77
        'ObjectType',
78
        'Summary',
79
        'Rules.Count'
80
    ];
81
82
    /**
83
     * Add to this list of classnames to disallow particular rules
84
     * from being selectable
85
     *
86
     * @var array[string]
0 ignored issues
show
Documentation Bug introduced by
The doc comment array[string] at position 1 could not be parsed: Expected ']' at position 1, but found '['.
Loading history...
87
     */
88
    private static $disallow_rules = [];
0 ignored issues
show
introduced by
The private property $disallow_rules is not used, and could be removed.
Loading history...
89
90
91
    /**
92
     * Add to this list of classnames to disallow particular types
93
     * from being selectable
94
     *
95
     * @var array[string]
0 ignored issues
show
Documentation Bug introduced by
The doc comment array[string] at position 1 could not be parsed: Expected ']' at position 1, but found '['.
Loading history...
96
     */
97
    private static $disallow_types = [
0 ignored issues
show
introduced by
The private property $disallow_types is not used, and could be removed.
Loading history...
98
        NotificationType::class
99
    ];
100
101
    public function getNotificationName(): string
102
    {
103
        return $this->i18n_singular_name();
104
    }
105
106
    public function getObjectType(): string
107
    {
108
        $class = $this->BaseClassName;
109
110
        if (!empty($class) && class_exists($class)) {
111
            return singleton($class)->i18n_singular_name();
112
        }
113
114
        return "";
115
    }
116
117
    public function getAllowedRules(): array
118
    {
119
        return $this->getAllowed(NotificationRule::class, 'disallow_rules');
120
    }
121
122
    public function isRuleAllowed(string $classname): bool
123
    {
124
        $rules = $this->getAllowedRules();
125
        return in_array($classname, $rules);
126
    }
127
128
    public function getAllowedTypes(): array
129
    {
130
        return $this->getAllowed(NotificationType::class, 'disallow_types');
131
    }
132
133
    public function isTypeAllowed(string $classname): bool
134
    {
135
        $types = $this->getAllowedTypes();
136
        return in_array($classname, $types);
137
    }
138
139
    /**
140
     * Attempt to generate a summary of this notification
141
     * and its rules
142
     *
143
     * @return string
144
     */
145
    public function getSummary(): string
146
    {
147
        $results = [];
148
149
        if ($this->StateCreated == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
150
            $results[] = _t(__CLASS__ . '.OnCreated', 'On Created');
151
        }
152
153
        if ($this->StateUpdated == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
154
            $results[] = _t(__CLASS__ . '.AnyUpdate', 'Any Update');
155
        }
156
157
        if ($this->StateDeleted == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
158
            $results[] =  _t(__CLASS__ . '.OnDeleted', 'On Deleted');
159
        }
160
161
        foreach ($this->Rules() as $rule) {
162
            /** @var NotificationRule $rule */
163
            $results[] = $rule->Summary;
164
        }
165
166
        foreach ($this->Types() as $type) {
167
            /** @var NotificationType $type */
168
            $results[] = $type->Summary;
0 ignored issues
show
Bug Best Practice introduced by
The property Summary does not exist on ilateral\SilverStripe\No...\Types\NotificationType. Since you implemented __get, consider adding a @property annotation.
Loading history...
169
        }
170
171
        return implode('; ', $results);
172
    }
173
174
    public function getCMSFields()
175
    {
176
        $self = $this;
177
178
        $this->beforeUpdateCMSFields(
179
            function ($fields) use ($self) {
180
                /** @var FieldList $fields */
181
                $fields->replaceField(
182
                    'BaseClassName',
183
                    DropdownField::create(
184
                        'BaseClassName',
185
                        $self->fieldLabel('BaseClassName'),
186
                        Notifier::getRegisteredObjectsArray()
187
                    )
188
                );
189
190
                /** @var GridField */
191
                $rules_field = $fields->dataFieldByName('Rules');
192
193
                if (!empty($rules_field)) {
194
                    $config = $rules_field->getConfig();
195
                    $classes = $this->getAllowedRules();
196
                    
197
                    $rules = new GridFieldAddNewMultiClass("buttons-before-right");
198
                    $rules->setClasses($classes);
199
200
                    $config
201
                        ->removeComponentsByType(GridFieldAddNewButton::class)
202
                        ->removeComponentsByType(GridFieldAddExistingAutocompleter::class)
203
                        ->addComponent($rules);
204
205
                    $rules_field->setConfig($config);
206
207
                    $fields->addFieldToTab('Root.Main', $rules_field);
208
                }
209
210
                /** @var GridField */
211
                $types_field = $fields->dataFieldByName('Types');
212
213
                if (!empty($types_field)) {
214
                    $config = $types_field->getConfig();
215
                    $classes = $this->getAllowedTypes();
216
217
                    $type = new GridFieldAddNewMultiClass("buttons-before-right");
218
                    $type->setClasses($classes);
219
220
                    $config
221
                        ->removeComponentsByType(GridFieldAddNewButton::class)
222
                        ->removeComponentsByType(GridFieldAddExistingAutocompleter::class)
223
                        ->addComponent($type);
224
                    
225
                    $types_field->setConfig($config);
226
227
                    $fields->addFieldToTab('Root.Main', $types_field);
228
                }
229
            }
230
        );
231
232
        return parent::getCMSFields();
233
    }
234
235
    /**
236
     * Return a list of allowed (rules or types) for this 
237
     */
238
    protected function getAllowed(string $classname, string $setting): array
239
    {
240
        $possible = ClassInfo::subclassesFor($classname, true);
241
        $disallow = Config::inst()->get(self::class, $setting);
242
243
        if (!is_array($disallow)) {
244
            throw new LogicException('Disallow Types must be an array');
245
        }
246
247
        $classes = [];
248
        
249
        foreach (array_values($possible) as $class) {
250
            if (!in_array($class, $disallow)) {
251
                $classes[] = $class;
252
            }
253
        }
254
            
255
        return $classes;
256
    }
257
}
258