Completed
Push — master ( ba0a85...cbab52 )
by
unknown
01:25
created

PerfectCMSImageDataExtension::get_height()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
dl 9
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
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
     * @var string $name name of Image Field template
56
     * @return string (link)
57
     */
58
    public function PerfectCMSAbsoluteImageLink($name)
59
    {
60
        $base = Director::baseURL();
61
        return $base . $this->PerfectCMSImageLink($name, null, '', true);
62
    }
63
64
    /**
65
     *
66
     * @param       string $name
67
     * @return string (HTML)
68
     */
69
    public function PerfectCMSImageTag($name)
70
    {
71
        $nonRetina = $this->PerfectCMSImageLinkNonRetina($name);
72
        $retina = $this->PerfectCMSImageLinkRetina($name);
73
        $width = self::get_width($name, true);
74
        $widthString = '';
75
        if ($width) {
76
            $widthString = ' width="'.$width.'"';
77
        }
78
        $heightString = '';
79
        $height = self::get_height($name, true);
80
        if ($height) {
81
            $heightString = ' height="'.$height.'"';
82
        }
83
        return
84
            '<img src="'.$nonRetina.'"'.
85
            ' srcset="'.$nonRetina.' 1x, '.$retina.' 2x" '.
86
            ' alt="'.Convert::raw2att($this->owner->Title).'"'.
87
            $widthString.
88
            $heightString.
89
90
            ' />';
91
    }
92
93
    /**
94
     * @param string            $name
95
     * @param object (optional) $backupObject
96
     * @param string (optional) $backupField
97
     *
98
     * @return string
99
     */
100
    public function PerfectCMSImageLink(
0 ignored issues
show
Coding Style introduced by
PerfectCMSImageLink uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
101
        $name,
102
        $backupObject = null,
103
        $backupField = '',
104
        $useRetina = null
105
    ) {
106
        if (isset($_GET['flush'])) {
107
            if (! Config::inst()->get('Image', 'force_resample')) {
108
                Config::inst()->update('Image', 'force_resample', true);
109
            }
110
        }
111
        $image = $this->owner;
112
        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...
113
            //we are all good ...
114
        } else {
115
            if (!$backupObject) {
116
                $backupObject = SiteConfig::current_site_config();
117
            }
118
            if (!$backupField) {
119
                $backupField = $name;
120
            }
121
            if ($backupObject->hasMethod($backupField)) {
122
                $image = $backupObject->$backupField();
123
            }
124
        }
125
126
        $perfectWidth = self::get_width($name, true);
127
        $perfectHeight = self::get_height($name, true);
128
129
        if ($image) {
130
            if ($image instanceof Image) {
131
                if ($image->exists()) {
132
                    //work out perfect with and height
133
                    if (!$useRetina) {
134
                        $useRetina = PerfectCMSImageDataExtension::use_retina($name);
135
                    } else {
136
                        $useRetina = $useRetina;
0 ignored issues
show
Bug introduced by
Why assign $useRetina to itself?

This checks looks for cases where a variable has been assigned to itself.

This assignement can be removed without consequences.

Loading history...
137
                    }
138
                    $crop = PerfectCMSImageDataExtension::crop($name);
139
                    $multiplier = 1;
140
                    if ($useRetina) {
141
                        $multiplier = 2;
142
                    }
143
                    $perfectWidth = $perfectWidth * $multiplier;
144
                    $perfectHeight = $perfectHeight  * $multiplier;
145
146
                    //get current width and height
147
                    $myWidth = $image->getWidth();
148
                    $myHeight = $image->getHeight();
149
                    // $backEndString = Image::get_backend();
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
150
                    // $backend = Injector::inst()->get($backEndString);
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
151
                    if ($perfectWidth && $perfectHeight) {
152
153
                        //if the height or the width are already perfect then we can not do anything about it.
154
                        if ($myWidth == $perfectWidth && $myHeight ==  $perfectHeight) {
155
                            $link = $image->Link();
156
                        } elseif ($crop) {
157
                            $link = $image->Fill($perfectWidth, $perfectHeight)->Link();
158
                        } elseif ($myWidth < $perfectWidth || $myHeight < $perfectHeight) {
159
                            $link = $image->Pad(
160
                                $perfectWidth,
161
                                $perfectHeight,
162
                                PerfectCMSImageDataExtension::get_padding_bg_colour($name)
0 ignored issues
show
Documentation introduced by
\PerfectCMSImageDataExte...adding_bg_colour($name) is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
163
                            )->Link();
164
                        } else {
165
                            $link = $image->FitMax($perfectWidth, $perfectHeight)->Link();
166
                        }
167
                    } elseif ($perfectWidth) {
168
                        if ($myWidth == $perfectWidth) {
169
                            $link = $image->Link();
170
                        } elseif ($crop) {
171
                            $link = $image->Fill($perfectHeight, $myHeight)->Link();
172
                        } else {
173
                            $link = $image->ScaleWidth($perfectWidth)->Link();
174
                        }
175
                    } elseif ($perfectHeight) {
176
                        if ($myHeight == $perfectHeight) {
177
                            $link = $image->Link();
178
                        } elseif ($crop) {
179
                            $link = $image->Fill($myWidth, $perfectHeight)->Link();
180
                        } else {
181
                            $link = $image->ScaleHeight($perfectHeight)->Link();
182
                        }
183
                    } else {
184
                        $link = $image->ScaleWidth($myWidth)->Link();
185
                    }
186
                    $path_parts = pathinfo($link);
187
188
                    if (class_exists('HashPathExtension')) {
189
                        if ($curr = Controller::curr()) {
190
                            if ($curr->hasMethod('HashPath')) {
191
                                $link = $curr->HashPath($link, false);
192
                            }
193
                        }
194
                    }
195
                    $imageClasses = Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_append_title_to_image_links_classes');
196
                    if (in_array($image->ClassName, $imageClasses) && $image->Title) {
197
                        $link = $this->replaceLastInstance(
198
                            '.'.$path_parts['extension'],
199
                            '.pci/'.$image->Title.'.'.$path_parts['extension'],
200
                            $link
201
                        );
202
                    }
203
204
                    return $link;
205
                }
206
            }
207
        }
208
        // no image -> provide placeholder if in DEV MODE only!!!
209
        if (Director::isDev()) {
210
            if ($perfectWidth || $perfectHeight) {
211
                if (!$perfectWidth) {
212
                    $perfectWidth = $perfectHeight;
213
                }
214
                if (!$perfectHeight) {
215
                    $perfectHeight = $perfectWidth;
216
                }
217
                $text = "$perfectWidth x $perfectHeight /2 = ".round($perfectWidth/2)." x ".round($perfectHeight/2)."";
218
219
                return 'https://placehold.it/'.($perfectWidth).'x'.($perfectHeight).'?text='.urlencode($text);
220
            } else {
221
                return 'https://placehold.it/500x500?text='.urlencode('no size set');
222
            }
223
        }
224
    }
225
226
    /**
227
     * @param string           $name
228
     *
229
     * @return boolean
230
     */
231
    public static function image_info_available($name)
232
    {
233
        $sizes = self::get_all_values_for_images();
234
        //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...
235
        return isset($sizes[$name]) ? true : false;
236
    }
237
238
239
    /**
240
     * @param string           $name
241
     *
242
     * @return boolean
243
     */
244
    public static function use_retina($name)
245
    {
246
        return self::get_one_value_for_image($name, "use_retina", true);
247
    }
248
249
250
    /**
251
     * @param string           $name
252
     *
253
     * @return boolean
254
     */
255
    public static function crop($name)
256
    {
257
        return self::get_one_value_for_image($name, "crop", false);
258
    }
259
260
    /**
261
     * @param string           $name
262
     * @param bool             $forceInteger
263
     *
264
     * @return int
265
     */
266 View Code Duplication
    public static function get_width($name, $forceInteger = false)
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...
267
    {
268
        $v = self::get_one_value_for_image($name, "width", 0);
269
        if ($forceInteger) {
270
            $v = intval($v) - 0;
271
        }
272
273
        return $v;
274
    }
275
276
    /**
277
     * @param string           $name
278
     * @param bool             $forceInteger
279
     *
280
     * @return int
281
     */
282 View Code Duplication
    public static function get_height($name, $forceInteger)
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...
283
    {
284
        $v = self::get_one_value_for_image($name, "height", 0);
285
        if ($forceInteger) {
286
            $v = intval($v) - 0;
287
        }
288
289
        return $v;
290
    }
291
292
    /**
293
     * @param string           $name
294
     *
295
     * @return string
296
     */
297
    public static function get_folder($name)
298
    {
299
        return self::get_one_value_for_image($name, "folder", 'other-images');
300
    }
301
302
    /**
303
     * @param string           $name
304
     *
305
     * @return int
306
     */
307
    public static function max_size_in_kilobytes($name)
308
    {
309
        return self::get_one_value_for_image($name, "max_size_in_kilobytes", 0);
310
    }
311
312
    /**
313
     * @param string           $name
314
     *
315
     * @return string
316
     */
317
    public static function get_file_type($name)
318
    {
319
        return self::get_one_value_for_image($name, "filetype", 'jpg');
320
    }
321
322
    /**
323
     * @param string           $name
324
     *
325
     * @return boolean
326
     */
327
    public static function get_enforce_size($name)
328
    {
329
        return self::get_one_value_for_image($name, "enforce_size", false);
330
    }
331
332
    /**
333
     * @param string           $name
334
     *
335
     * @return boolean
336
     */
337
    public static function get_padding_bg_colour($name)
338
    {
339
        return self::get_one_value_for_image(
340
            $name,
341
            "padding_bg_colour",
342
            Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_background_padding_color')
343
        );
344
    }
345
346
    /**
347
     * @param string $name
348
     * @param int    $key
349
     * @param mixed  $default
350
     *
351
     * @return mixed
352
     */
353
    private static function get_one_value_for_image($name, $key, $default = '')
354
    {
355
        $sizes = self::get_all_values_for_images();
356
        //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...
357
        if (isset($sizes[$name])) {
358
            if (isset($sizes[$name][$key])) {
359
                return $sizes[$name][$key];
360
            }
361
        } else {
362
            user_error('no information for image with name: '.$name);
363
        }
364
365
        return $default;
366
    }
367
368
    /**
369
     * @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...
370
     */
371
    private static function get_all_values_for_images()
372
    {
373
        return Config::inst()->get('PerfectCMSImageDataExtension', 'perfect_cms_images_image_definitions');
374
    }
375
376
    /**
377
     * replace the last instance of a string occurence.
378
     *
379
     * @param  string $search  needle
380
     * @param  string $replace new needle
381
     * @param  string $subject haystack
382
     *
383
     * @return string
384
     */
385
    private function replaceLastInstance($search, $replace, $subject)
386
    {
387
        $pos = strrpos($subject, $search);
388
389
        if ($pos !== false) {
390
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
391
        }
392
393
        return $subject;
394
    }
395
}
396