Completed
Push — master ( f757b6...62b6a3 )
by
unknown
02:02
created

PerfectCMSImageLinkRetina()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * defines the image sizes
5
 * and default upload folder.
6
 */
7
class PerfectCMSImageDataExtension extends DataExtension
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...
8
{
9
    /**
10
     * background image for padded images...
11
     *
12
     * @var string
13
     */
14
    private static $perfect_cms_images_background_padding_color = '#cccccc';
0 ignored issues
show
Unused Code introduced by
The property $perfect_cms_images_background_padding_color 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...
15
16
    /***
17
     * sizes of the images
18
     *     width: 3200
19
     *     height: 3200
20
     *     folder: "myfolder"
21
     *     filetype: "try jpg"
22
     *
23
     * @var array
24
     *
25
     */
26
    private static $perfect_cms_images_image_definitions = array();
0 ignored issues
show
Unused Code introduced by
The property $perfect_cms_images_image_definitions 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...
27
28
    /***
29
     *  Images Titles will be appended to the links only
30
     *  if the ClassName of the Image is in this array
31
     * @var array
32
     *
33
     */
34
    private static $perfect_cms_images_append_title_to_image_links_classes = array();
0 ignored issues
show
Unused Code introduced by
The property $perfect_cms_images_appe..._to_image_links_classes 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...
35
36
    /**
37
     * @var string $name name of Image Field template
38
     * @return string (link)
39
     */
40
    public function PerfectCMSImageLinkNonRetina($name)
41
    {
42
        return $this->PerfectCMSImageLink($name, null, '', false);
43
    }
44
45
    /**
46
     * @var string $name name of Image Field template
47
     * @return string (link)
48
     */
49
    public function PerfectCMSImageLinkRetina($name)
50
    {
51
        return $this->PerfectCMSImageLink($name, null, '', true);
52
    }
53
54
    /**
55
     * @param string            $name
56
     * @param object (optional) $backupObject
57
     * @param string (optional) $backupField
58
     *
59
     * @return string
60
     */
61
    public function PerfectCMSImageLink(
62
        $name,
63
        $backupObject = null,
64
        $backupField = '',
65
        $isRetina = true
66
    ) {
67
        if (! Config::inst()->get('Image', 'force_resample')) {
68
            Config::inst()->update('Image', 'force_resample', true);
69
        }
70
        $image = $this->owner;
71
        if ($image && $image->exists()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
72
            //we are all good ...
73
        } else {
74
            if (!$backupObject) {
75
                $backupObject = SiteConfig::current_site_config();
76
            }
77
            if (!$backupField) {
78
                $backupField = $name;
79
            }
80
            if ($backupObject->hasMethod($backupField)) {
81
                $image = $backupObject->$backupField();
82
            }
83
        }
84
85
        $perfectWidth = (intval(self::get_width($name)) - 0);
86
        $perfectHeight = (intval(self::get_height($name)) - 0);
87
        if ($isRetina) {
88
            $perfectWidth = $perfectWidth * 2;
89
            $perfectHeight = $perfectHeight  * 2;
90
        }
91
        if ($image) {
92
            if ($image instanceof Image) {
93
                if ($image->exists()) {
94
                    //get preferred width and height
95
                    $myWidth = $image->getWidth();
96
                    $myHeight = $image->getHeight();
97
                    $backEndString = Image::get_backend();
98
                    $backend = Injector::inst()->get($backEndString);
0 ignored issues
show
Unused Code introduced by
$backend is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
99
                    if ($perfectWidth && $perfectHeight) {
100
                        if ($myWidth == $perfectWidth || $myHeight ==  $perfectHeight) {
101
                            $link = $image->ScaleWidth($myWidth)->Link();
102
                        } elseif ($myWidth < $perfectWidth || $myHeight < $perfectHeight) {
103
                            $link = $image->Pad(
104
                                $perfectWidth,
105
                                $perfectHeight,
106
                                Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_background_padding_color')
107
                            )->Link();
108
                        } elseif ($myWidth > $perfectWidth || $myHeight > $perfectHeight) {
109
                            $link = $image->FitMax($perfectWidth, $perfectHeight)->Link();
110
                        }
111
                    } elseif ($perfectWidth) {
112
                        $link = $image->ScaleWidth($perfectWidth)->Link();
113
                    } elseif ($perfectHeight) {
114
                        $link = $image->ScaleHeight($perfectHeight)->Link();
115
                    } else {
116
                        $link = $image->ScaleWidth($myWidth)->Link();
117
                    }
118
                    $path_parts = pathinfo($link);
0 ignored issues
show
Bug introduced by
The variable $link does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
119
120
                    if (class_exists('HashPathExtension')) {
121
                        if ($curr = Controller::curr()) {
122
                            if ($curr->hasMethod('HashPath')) {
123
                                $link = $curr->HashPath($link, false);
124
                            }
125
                        }
126
                    }
127
                    $imageClasses = Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_append_title_to_image_links_classes');
128
                    if(in_array($image->ClassName, $imageClasses) && $image->Title){
129
                        $link = $this->replaceLastInstance(
130
                            '.'.$path_parts['extension'],
131
                            '.pci/'.$image->Title.'.'.$path_parts['extension'],
132
                            $link
133
                        );
134
                    }
135
                    return $link;
136
                }
137
            }
138
        }
139
        // no image -> provide placeholder
140
        if ($perfectWidth || $perfectHeight) {
141
            if (!$perfectWidth) {
142
                $perfectWidth = $perfectHeight;
143
            }
144
            if (!$perfectHeight) {
145
                $perfectHeight = $perfectWidth;
146
            }
147
            $text = "$perfectWidth x $perfectHeight /2 = ".round($perfectWidth/2)." x ".round($perfectHeight/2)."";
148
149
            return 'https://placehold.it/'.($perfectWidth).'x'.($perfectHeight).'?text='.urlencode($text);
150
        } else {
151
            return 'https://placehold.it/500x500?text='.urlencode('no size set');
152
        }
153
    }
154
155
    /**
156
     * @param string           $name
157
     * @param Image (optional) $image
158
     *
159
     * @return int
160
     */
161
    public static function get_width($name)
162
    {
163
        return self::get_one_value_for_image($name, "width", 0);
164
    }
165
166
    /**
167
     * @param string           $name
168
     * @param Image (optional) $image
169
     *
170
     * @return int
171
     */
172
    public static function get_height($name)
173
    {
174
        return self::get_one_value_for_image($name, "height", 0);
175
    }
176
177
    /**
178
     * @param string           $name
179
     * @param Image (optional) $image
180
     *
181
     * @return string
182
     */
183
    public static function get_folder($name)
184
    {
185
        return self::get_one_value_for_image($name, "folder", 'other-images');
186
    }
187
188
    /**
189
     * @param string           $name
190
     * @param Image (optional) $image
191
     *
192
     * @return string
193
     */
194
    public static function get_file_type($name)
195
    {
196
        return self::get_one_value_for_image($name, "filetype", 'jpg');
197
    }
198
199
    /**
200
     * @param string           $name
201
     * @param Image (optional) $image
202
     *
203
     * @return boolean
204
     */
205
    public static function get_enforce_size($name)
206
    {
207
        return self::get_one_value_for_image($name, "enforce_size", true);
208
    }
209
210
    /**
211
     * @param string $name
212
     * @param int    $key
213
     * @param mixed  $default
214
     *
215
     * @return mixed
216
     */
217
    private static function get_one_value_for_image($name, $key, $default = '')
218
    {
219
        $sizes = self::get_all_values_for_images();
220
        //print_r($sizes);die();
0 ignored issues
show
Unused Code Comprehensibility introduced by
89% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
221
        if (isset($sizes[$name])) {
222
            if (isset($sizes[$name][$key])) {
223
                return $sizes[$name][$key];
224
            }
225
        } else {
226
            user_error('no information for image with name: '.$name);
227
        }
228
229
        return $default;
230
    }
231
232
    /**
233
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|integer|double|string|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
234
     */
235
    private static function get_all_values_for_images()
236
    {
237
        return Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_image_definitions');
238
    }
239
240
    /**
241
     * replace the last instance of a string occurence.
242
     *
243
     * @param  string $search  needle
244
     * @param  string $replace new needle
245
     * @param  string $subject haystack
246
     *
247
     * @return string
248
     */
249
    private function replaceLastInstance($search, $replace, $subject)
250
    {
251
        $pos = strrpos($subject, $search);
252
253
        if($pos !== false)
254
        {
255
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
256
        }
257
258
        return $subject;
259
    }
260
261
}
262