ImageStyle::CMSEditLink()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
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
    private static $default_style = 'unstyled-image';
0 ignored issues
show
Unused Code introduced by
The property $default_style 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...
8
9
    public static function get_default_style()
10
    {
11
        $defaultStyle = ImageStyle::get()->filter(
12
            [
13
                'ClassNameForCSS' => Config::inst()->get('ImageStyle', 'default_style')
14
            ]
15
        )->first();
16
        if (! $defaultStyle) {
17
            $defaultStyle = ImageStyle::get()->first();
18
            if (! $defaultStyle) {
19
                user_error('Could not find a default Style.');
20
            }
21
        }
22
23
        return $defaultStyle;
24
    }
25
26
    /**
27
     * see _config folder for details ...
28
     * @var array
29
     */
30
    private static $record_defaults = [];
0 ignored issues
show
Unused Code introduced by
The property $record_defaults 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...
31
32
33
    #######################
34
    ### Names Section
35
    #######################
36
37
    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...
Unused Code introduced by
The property $singular_name 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...
38
39
    public function i18n_singular_name()
40
    {
41
        return _t('ImageStyle.SINGULAR_NAME', 'Image Style');
42
    }
43
44
    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...
Unused Code introduced by
The property $plural_name 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...
45
46
    public function i18n_plural_name()
47
    {
48
        return _t('ImageStyle.PLURAL_NAME', 'Image Styles');
49
    }
50
51
52
    #######################
53
    ### Model Section
54
    #######################
55
56
    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...
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...
57
        'Title' => 'Varchar',
58
        'ClassNameForCSS' => 'Varchar',
59
        'Description' => 'Text',
60
        'Var1Name' => 'Varchar',
61
        'Var1Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
62
        'Var1Options' => 'Varchar(200)',
63
        'Var1Description' => 'Varchar(200)',
64
65
        'Var2Name' => 'Varchar',
66
        'Var2Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
67
        'Var2Options' => 'Varchar(200)',
68
        'Var2Description' => 'Varchar(200)',
69
70
        'Var3Name' => 'Varchar',
71
        'Var3Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
72
        'Var3Options' => 'Varchar(200)',
73
        'Var3Description' => 'Varchar(200)',
74
75
        'Var4Name' => 'Varchar',
76
        'Var4Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
77
        'Var4Options' => 'Varchar(200)',
78
        'Var4Description' => 'Varchar(200)',
79
80
        'Var5Name' => 'Varchar',
81
        'Var5Type' => 'Enum(\'Pixels,Percentage,Options\', \'Pixels\')',
82
        'Var5Options' => 'Varchar(200)',
83
        'Var5Description' => 'Varchar(200)',
84
85
    ];
86
87
    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...
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...
88
        'ImagesWithStyle' => 'ImageWithStyle'
89
    ];
90
91
92
    #######################
93
    ### Further DB Field Details
94
    #######################
95
96
    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...
Unused Code introduced by
The property $indexes 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...
97
        'Title' => true
98
    ];
99
100
    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...
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...
101
        'Title' => 'ASC'
102
    ];
103
104
    private static $required_fields = [
0 ignored issues
show
Unused Code introduced by
The property $required_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...
105
        'Title',
106
        'ClassNameForCSS'
107
    ];
108
109
    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...
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...
110
        'Title' => 'PartialMatchFilter',
111
        'Description' => 'PartialMatchFilter',
112
        'ClassNameForCSS' => 'PartialMatchFilter'
113
    ];
114
115
116
    #######################
117
    ### Field Names and Presentation Section
118
    #######################
119
120
    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...
Unused Code introduced by
The property $field_labels 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...
121
        'Title' => 'Style',
122
123
        'Var1Name' => 'Variable 1 Label',
124
        'Var1Type' => 'Variable 1 Type',
125
        'Var1Options' => 'Variable 1 Options',
126
        'Var1Description' => 'Variable 1 Description',
127
128
        'Var2Name' => 'Variable 2 Label',
129
        'Var2Type' => 'Variable 2 Type',
130
        'Var2Options' => 'Variable 1 Options',
131
        'Var2Description' => 'Variable 1 Description',
132
133
        'Var3Name' => 'Variable 3 Label',
134
        'Var3Type' => 'Variable 3 Type',
135
        'Var3Options' => 'Variable 1 Options',
136
        'Var4Description' => 'Variable 1 Description',
137
138
        'Var4Name' => 'Variable 4 Label',
139
        'Var4Type' => 'Variable 4 Type',
140
        'Var4Options' => 'Variable 4 Options',
141
        'Var4Description' => 'Variable 4 Description',
142
143
        'Var5Name' => 'Variable 5 Label',
144
        'Var5Type' => 'Variable 5 Type',
145
        'Var5Options' => 'Variable 5 Options',
146
        'Var5Description' => 'Variable 5 Description',
147
    ];
148
149
    private static $field_labels_right = [];
0 ignored issues
show
Unused Code introduced by
The property $field_labels_right 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...
150
151
    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...
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...
152
        'Title' => 'Style',
153
        'ImagesWithStyle.Count' => 'Usage Count'
154
    ];
155
156
157
    #######################
158
    ### Casting Section
159
    #######################
160
161
162
    #######################
163
    ### can Section
164
    #######################
165
166
    public function canCreate($member = null)
167
    {
168
        return false;
169
    }
170
171
    public function canEdit($member = null)
172
    {
173
        //we block edits in CMS
174
        return parent::canEdit($member);
175
    }
176
177
    public function canDelete($member = null)
178
    {
179
        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...
180
            return parent::canDelete($member);
181
        }
182
183
        return false;
184
    }
185
186
187
188
    #######################
189
    ### write Section
190
    #######################
191
192
193
194
195 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...
196
    {
197
        $result = parent::validate();
198
        $fieldLabels = $this->FieldLabels();
199
        $indexes = $this->Config()->get('indexes');
200
        $requiredFields = $this->Config()->get('required_fields');
201
        if (is_array($requiredFields)) {
202
            foreach ($requiredFields as $field) {
203
                $value = $this->$field;
204
                if (! $value) {
205
                    $fieldWithoutID = $field;
206
                    if (substr($fieldWithoutID, -2) === 'ID') {
207
                        $fieldWithoutID = substr($fieldWithoutID, 0, -2);
208
                    }
209
                    $myName = isset($fieldLabels[$fieldWithoutID]) ? $fieldLabels[$fieldWithoutID] : $fieldWithoutID;
210
                    $result->error(
211
                        _t(
212
                            'ImageStyle.'.$field.'_REQUIRED',
213
                            $myName.' is required'
214
                        ),
215
                        'REQUIRED_ImageStyle_'.$field
216
                    );
217
                }
218
                if (isset($indexes[$field]) && isset($indexes[$field]['type']) && $indexes[$field]['type'] === 'unique') {
219
                    $id = (empty($this->ID) ? 0 : $this->ID);
220
                    $count = ImageStyle::get()
221
                        ->filter(array($field => $value))
222
                        ->exclude(array('ID' => $id))
223
                        ->count();
224
                    if ($count > 0) {
225
                        $myName = $fieldLabels['$field'];
226
                        $result->error(
227
                            _t(
228
                                'ImageStyle.'.$field.'_UNIQUE',
229
                                $myName.' needs to be unique'
230
                            ),
231
                            'UNIQUE_ImageStyle_'.$field
232
                        );
233
                    }
234
                }
235
            }
236
        }
237
238
        return $result;
239
    }
240
241
    public function onBeforeWrite()
242
    {
243
        parent::onBeforeWrite();
244
        $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...
245
        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...
246
            $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...
247
        }
248
        //...
249
    }
250
251
    public function onAfterWrite()
252
    {
253
        parent::onAfterWrite();
254
        //...
255
    }
256
257
    public function requireDefaultRecords()
258
    {
259
        parent::requireDefaultRecords();
260
        //...
261
        $defaults = $this->Config()->record_defaults;
262
        $currentOnes = array_flip(ImageStyle::get()->column('ID'));
263
        $imageNames = Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_image_definitions');
264
        foreach ($defaults as $defaultValues) {
265
            foreach ($defaultValues as $field => $value) {
266
                if (is_array($value)) {
267
                    $defaultValues[$field] = serialize($value);
268
                }
269
            }
270
            $obj = ImageStyle::get()->filter(['Title' => $defaultValues['Title']])->first();
271
            if (!$obj) {
272
                $obj = ImageStyle::create($defaultValues);
273
            } else {
274
                foreach ($obj->db() as $field => $type) {
275
                    $obj->$field = null;
276
                }
277
                foreach ($defaultValues as $field => $value) {
278
                    $obj->$field = $value;
279
                }
280
            }
281
            unset($currentOnes[$obj->ID]);
282
            $obj->write();
283
            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...
284
                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...
285
            }
286
        }
287
        foreach ($currentOnes as $id) {
288
            $obj = ImageStyle::get()->byID($id);
289
            if ($obj && $obj->canDelete()) {
290
                $obj->delete();
291
            }
292
        }
293
    }
294
295
296
    #######################
297
    ### Import / Export Section
298
    #######################
299
300
    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...
301
    {
302
        //..
303
        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...
304
    }
305
306
307
308
    #######################
309
    ### CMS Edit Section
310
    #######################
311
312
313
    public function CMSEditLink()
314
    {
315
        $controller = singleton("tba");
316
317
        return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/".$this->ID."/edit";
318
    }
319
320
    public function CMSAddLink()
321
    {
322
        $controller = singleton("tba");
323
324
        return $controller->Link().$this->ClassName."/EditForm/field/".$this->ClassName."/item/new";
325
    }
326
327
328
    public function getCMSFields()
329
    {
330
        $fields = parent::getCMSFields();
331
332
        //do first??
333
        $rightFieldDescriptions = $this->Config()->get('field_labels_right');
334 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...
335
            $formField = $fields->DataFieldByName($field);
336
            if (! $formField) {
337
                $formField = $fields->DataFieldByName($field.'ID');
338
            }
339
            if ($formField) {
340
                $formField->setDescription($desc);
341
            }
342
        }
343
344
        // move variables to their own tab
345
        for ($i = 1; $i < 6; $i++) {
346
            if ($this->HasStyleVariable('Var'.$i)) {
347
                $fieldsToAdd = [
348
                    $fields->dataFieldByName('Var'.$i.'Name'),
349
                    $fields->dataFieldByName('Var'.$i.'Type'),
350
                    $fields->dataFieldByName('Var'.$i.'Options'),
351
                    $fields->dataFieldByName('Var'.$i.'Description')
352
                ];
353
                $fields->addFieldsToTab(
354
                    'Root.Variable '.$i,
355
                    $fieldsToAdd
356
                );
357
            } else {
358
                $fields->removeByName('Var'.$i.'Name');
359
                $fields->removeByName('Var'.$i.'Type');
360
                $fields->removeByName('Var'.$i.'Options');
361
                $fields->removeByName('Var'.$i.'Description');
362
            }
363
        }
364
        $fields->removeByName('ImagesWithStyle');
365
366
        //make everything readonly
367
        foreach ($fields->saveableFields() as $field) {
368
            $fieldName = $field->getName();
369
            $oldField = $fields->dataFieldByName($fieldName);
370
            if ($oldField) {
371
                $newField = $oldField->performReadonlyTransformation();
372
                $fields->replaceField($fieldName, $newField);
373
            }
374
        }
375
376
        return $fields;
377
    }
378
379
380
    public function HasStyleVariable($varName)
381
    {
382
        $name = $varName.'Name';
383
        $type = $varName.'Type';
384
        $hasBase = $this->$name && $this->$type ? true : false;
385
        if ($this->$type === 'Options') {
386
            return $hasBase && is_array($this->OptionsAsArray($varName)) ? true : false;
387
        } else {
388
            return $hasBase;
389
        }
390
    }
391
    public function HasOptionsAsArray($varName)
392
    {
393
        $options = $this->OptionsAsArray($varName);
394
395
        return count($options) ? true : false;
396
    }
397
398
    public function OptionsAsArray($varName)
399
    {
400
        $options = $varName.'Options';
401
        $array = [];
402
        if ($this->$options) {
403
            $array = @unserialize($this->$options);
404
        }
405
        if (is_array($array)) {
406
            return $array;
407
        }
408
409
        return [];
410
    }
411
}
412