Completed
Push — master ( 00e697...ce1abf )
by Nicolaas
01:18
created

ImageStyle::requireDefaultRecords()   C

Complexity

Conditions 11
Paths 39

Size

Total Lines 37
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 25
nc 39
nop 0

How to fix   Complexity   

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
4
5
class ImageStyle extends DataObject
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...
6
{
7
8
    private static $default_style = 'unstyled-image';
9
10
    public static function get_default_style()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
11
    {
12
        $defaultStyle = ImageStyle::get()->filter(
13
            [
14
                'ClassNameForCSS' => Config::inst()->get('ImageStyle', 'default_style')
15
            ]
16
        )->first();
17
        if(! $defaultStyle) {
18
            $defaultStyle = ImageStyle::get()->first();
19
            if(! $defaultStyle) {
20
                user_error('Could not find a default Style.');
21
            }
22
        }
23
24
        return $defaultStyle;
25
    }
26
27
    /**
28
     * see _config folder for details ...
29
     * @var array
30
     */
31
    private static $record_defaults = [];
32
33
34
    #######################
35
    ### Names Section
36
    #######################
37
38
    private static $singular_name = 'Image Style';
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...
39
40
    public function i18n_singular_name()
41
    {
42
        return _t('ImageStyle.SINGULAR_NAME', 'Image Style');
43
    }
44
45
    private static $plural_name = 'Image Styles';
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...
46
47
    public function i18n_plural_name()
48
    {
49
        return _t('ImageStyle.PLURAL_NAME', 'Image Styles');
50
    }
51
52
53
    #######################
54
    ### Model Section
55
    #######################
56
57
    private static $db = [
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...
58
        'Title' => 'Varchar',
59
        'ClassNameForCSS' => 'Varchar',
60
        'Description' => 'Text',
61
        'Var1Name' => 'Varchar',
62
        'Var1Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
63
        'Var1Options' => 'Varchar(200)',
64
        'Var1Description' => 'Varchar(200)',
65
66
        'Var2Name' => 'Varchar',
67
        'Var2Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
68
        'Var2Options' => 'Varchar(200)',
69
        'Var2Description' => 'Varchar(200)',
70
71
        'Var3Name' => 'Varchar',
72
        'Var3Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
73
        'Var3Options' => 'Varchar(200)',
74
        'Var3Description' => 'Varchar(200)',
75
76
        'Var4Name' => 'Varchar',
77
        'Var4Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
78
        'Var4Options' => 'Varchar(200)',
79
        'Var4Description' => 'Varchar(200)',
80
81
        'Var5Name' => 'Varchar',
82
        'Var5Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
83
        'Var5Options' => 'Varchar(200)',
84
        'Var5Description' => 'Varchar(200)',
85
86
    ];
87
88
    private static $has_many = [
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...
89
        'ImagesWithStyle' => 'ImageWithStyle'
90
    ];
91
92
93
    #######################
94
    ### Further DB Field Details
95
    #######################
96
97
    private static $indexes = [
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...
98
        'Title' => true
99
    ];
100
101
    private static $default_sort = [
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...
102
        'Title' => 'ASC'
103
    ];
104
105
    private static $required_fields = [
106
        'Title',
107
        'ClassNameForCSS'
108
    ];
109
110
    private static $searchable_fields = [
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...
111
        'Title' => 'PartialMatchFilter',
112
        'Description' => 'PartialMatchFilter',
113
        'ClassNameForCSS' => 'PartialMatchFilter'
114
    ];
115
116
117
    #######################
118
    ### Field Names and Presentation Section
119
    #######################
120
121
    private static $field_labels = [
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...
122
        'Title' => 'Style',
123
124
        'Var1Name' => 'Variable 1 Label',
125
        'Var1Type' => 'Variable 1 Type',
126
        'Var1Options' => 'Variable 1 Options',
127
        'Var1Description' => 'Variable 1 Description',
128
129
        'Var2Name' => 'Variable 2 Label',
130
        'Var2Type' => 'Variable 2 Type',
131
        'Var2Options' => 'Variable 1 Options',
132
        'Var2Description' => 'Variable 1 Description',
133
134
        'Var3Name' => 'Variable 3 Label',
135
        'Var3Type' => 'Variable 3 Type',
136
        'Var3Options' => 'Variable 1 Options',
137
        'Var4Description' => 'Variable 1 Description',
138
139
        'Var4Name' => 'Variable 4 Label',
140
        'Var4Type' => 'Variable 4 Type',
141
        'Var4Options' => 'Variable 4 Options',
142
        'Var4Description' => 'Variable 4 Description',
143
144
        'Var5Name' => 'Variable 5 Label',
145
        'Var5Type' => 'Variable 5 Type',
146
        'Var5Options' => 'Variable 5 Options',
147
        'Var5Description' => 'Variable 5 Description',
148
    ];
149
150
    private static $field_labels_right = [];
151
152
    private static $summary_fields = [
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...
153
        'Title' => 'Style',
154
        'ImagesWithStyle.Count' => 'Usage Count'
155
    ];
156
157
158
    #######################
159
    ### Casting Section
160
    #######################
161
162
163
    #######################
164
    ### can Section
165
    #######################
166
167
    public function canCreate($member = null)
168
    {
169
        return false;
170
    }
171
172
    public function canEdit($member = null)
173
    {
174
        //we block edits in CMS
175
        return parent::canEdit($member);
176
    }
177
178
    public function canDelete($member = null)
179
    {
180
        if ($this->ImagesWithStyle()->count() === 0) {
0 ignored issues
show
Documentation Bug introduced by
The method ImagesWithStyle does not exist on object<ImageStyle>? 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...
181
            return parent::canDelete($member);
182
        }
183
184
        return false;
185
    }
186
187
188
189
    #######################
190
    ### write Section
191
    #######################
192
193
194
195
196 View Code Duplication
    public function validate()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
197
    {
198
        $result = parent::validate();
199
        $fieldLabels = $this->FieldLabels();
200
        $indexes = $this->Config()->get('indexes');
201
        $requiredFields = $this->Config()->get('required_fields');
202
        if (is_array($requiredFields)) {
203
            foreach ($requiredFields as $field) {
204
                $value = $this->$field;
205
                if (! $value) {
206
                    $fieldWithoutID = $field;
207
                    if (substr($fieldWithoutID, -2) === 'ID') {
208
                        $fieldWithoutID = substr($fieldWithoutID, 0, -2);
209
                    }
210
                    $myName = isset($fieldLabels[$fieldWithoutID]) ? $fieldLabels[$fieldWithoutID] : $fieldWithoutID;
211
                    $result->error(
212
                        _t(
213
                            'ImageStyle.'.$field.'_REQUIRED',
214
                            $myName.' is required'
215
                        ),
216
                        'REQUIRED_ImageStyle_'.$field
217
                    );
218
                }
219
                if (isset($indexes[$field]) && isset($indexes[$field]['type']) && $indexes[$field]['type'] === 'unique') {
220
                    $id = (empty($this->ID) ? 0 : $this->ID);
221
                    $count = ImageStyle::get()
222
                        ->filter(array($field => $value))
223
                        ->exclude(array('ID' => $id))
224
                        ->count();
225
                    if ($count > 0) {
226
                        $myName = $fieldLabels['$field'];
227
                        $result->error(
228
                            _t(
229
                                'ImageStyle.'.$field.'_UNIQUE',
230
                                $myName.' needs to be unique'
231
                            ),
232
                            'UNIQUE_ImageStyle_'.$field
233
                        );
234
                    }
235
                }
236
            }
237
        }
238
239
        return $result;
240
    }
241
242
    public function onBeforeWrite()
243
    {
244
        parent::onBeforeWrite();
245
        $this->ClassNameForCSS = preg_replace('/\W+/', '-', strtolower(strip_tags($this->ClassNameForCSS)));
0 ignored issues
show
Bug introduced by
The property ClassNameForCSS 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...
246
        if (! $this->ClassNameForCSS) {
0 ignored issues
show
Bug introduced by
The property ClassNameForCSS 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...
247
            $this->ClassNameForCSS = 'image-with-style-'.$this->ID;
0 ignored issues
show
Bug introduced by
The property ClassNameForCSS 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...
248
        }
249
        //...
250
    }
251
252
    public function onAfterWrite()
253
    {
254
        parent::onAfterWrite();
255
        //...
256
    }
257
258
    public function requireDefaultRecords()
259
    {
260
        parent::requireDefaultRecords();
261
        //...
262
        $defaults = $this->Config()->record_defaults;
263
        $currentOnes = array_flip(ImageStyle::get()->column('ID'));
264
        $imageNames = Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_image_definitions');
265
        foreach ($defaults as $defaultValues) {
266
            foreach ($defaultValues as $field => $value) {
267
                if (is_array($value)) {
268
                    $defaultValues[$field] = serialize($value);
269
                }
270
            }
271
            $obj = ImageStyle::get()->filter(['Title' => $defaultValues['Title']])->first();
272
            if (!$obj) {
273
                $obj = ImageStyle::create($defaultValues);
274
            } else {
275
                foreach ($obj->db() as $field => $type) {
276
                    $obj->$field = null;
277
                }
278
                foreach ($defaultValues as $field => $value) {
279
                    $obj->$field = $value;
280
                }
281
            }
282
            unset($currentOnes[$obj->ID]);
283
            $obj->write();
284
            if (! isset($imageNames[$obj->ClassNameForCSS])) {
0 ignored issues
show
Bug introduced by
The property ClassNameForCSS 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...
285
                user_error('You need to define a perfect CMS image with the following name: '.$obj->ClassNameForCSS);
0 ignored issues
show
Bug introduced by
The property ClassNameForCSS 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...
286
            }
287
        }
288
        foreach ($currentOnes as $id) {
289
            $obj = ImageStyle::get()->byID($id);
290
            if ($obj && $obj->canDelete()) {
291
                $obj->delete();
292
            }
293
        }
294
    }
295
296
297
    #######################
298
    ### Import / Export Section
299
    #######################
300
301
    public function getExportFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
302
    {
303
        //..
304
        return parent::getExportFields();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DataObject as the method getExportFields() does only exist in the following sub-classes of DataObject: ImageStyle, ImageWithStyle, ImagesWithStyleSelection. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
305
    }
306
307
308
309
    #######################
310
    ### CMS Edit Section
311
    #######################
312
313
314
    public function CMSEditLink()
315
    {
316
        $controller = singleton("tba");
317
318
        return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/".$this->ID."/edit";
319
    }
320
321
    public function CMSAddLink()
322
    {
323
        $controller = singleton("tba");
324
325
        return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/new";
326
    }
327
328
329
    public function getCMSFields()
330
    {
331
        $fields = parent::getCMSFields();
332
333
        //do first??
334
        $rightFieldDescriptions = $this->Config()->get('field_labels_right');
335 View Code Duplication
        foreach ($rightFieldDescriptions as $field => $desc) {
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...
336
            $formField = $fields->DataFieldByName($field);
337
            if (! $formField) {
338
                $formField = $fields->DataFieldByName($field.'ID');
339
            }
340
            if ($formField) {
341
                $formField->setDescription($desc);
342
            }
343
        }
344
345
        // move variables to their own tab
346
        for ($i = 1; $i < 6; $i++) {
347
            if ($this->HasStyleVariable('Var'.$i)) {
348
                $fieldsToAdd = [
349
                    $fields->dataFieldByName('Var'.$i.'Name'),
350
                    $fields->dataFieldByName('Var'.$i.'Type'),
351
                    $fields->dataFieldByName('Var'.$i.'Options'),
352
                    $fields->dataFieldByName('Var'.$i.'Description')
353
                ];
354
                $fields->addFieldsToTab(
355
                    'Root.Variable '.$i,
356
                    $fieldsToAdd
357
                );
358
            } else {
359
                $fields->removeByName('Var'.$i.'Name');
360
                $fields->removeByName('Var'.$i.'Type');
361
                $fields->removeByName('Var'.$i.'Options');
362
                $fields->removeByName('Var'.$i.'Description');
363
            }
364
        }
365
        $fields->removeByName('ImagesWithStyle');
366
367
        //make everything readonly
368
        foreach ($fields->saveableFields() as $field) {
369
            $fieldName = $field->getName();
370
            $oldField = $fields->dataFieldByName($fieldName);
371
            if ($oldField) {
372
                $newField = $oldField->performReadonlyTransformation();
373
                $fields->replaceField($fieldName, $newField);
374
            }
375
        }
376
377
        return $fields;
378
    }
379
380
381
    public function HasStyleVariable($varName)
382
    {
383
        $name = $varName.'Name';
384
        $type = $varName.'Type';
385
        $hasBase = $this->$name && $this->$type ? true : false;
386
        if ($this->$type === 'Options') {
387
            return $hasBase && is_array($this->OptionsAsArray($varName)) ? true : false;
388
        } else {
389
            return $hasBase;
390
        }
391
    }
392
    public function HasOptionsAsArray($varName)
393
    {
394
        $options = $this->OptionsAsArray($varName);
395
396
        return count($options) ? true : false;
397
    }
398
399
    public function OptionsAsArray($varName) : array
400
    {
401
        $options = $varName.'Options';
402
        $array = [];
403
        if ($this->$options) {
404
            $array = @unserialize($this->$options);
405
        }
406
        if (is_array($array)) {
407
            return $array;
408
        }
409
410
        return [];
411
    }
412
}
413