Crop::limitToImageBoundaries()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 10
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 12
1
<?php
2
3
namespace League\Glide\Manipulators;
4
5
use Intervention\Image\Image;
6
7
/**
8
 * @property string $crop
9
 */
10
class Crop extends BaseManipulator
11
{
12
    /**
13
     * Perform crop image manipulation.
14
     * @param  Image $image The source image.
15
     * @return Image The manipulated image.
16
     */
17
    public function run(Image $image)
18
    {
19
        $coordinates = $this->getCoordinates($image);
20
21
        if ($coordinates) {
22
            $coordinates = $this->limitToImageBoundaries($image, $coordinates);
23
24
            $image->crop(
25
                $coordinates[0],
26
                $coordinates[1],
27
                $coordinates[2],
28
                $coordinates[3]
29
            );
30
        }
31
32
        return $image;
33
    }
34
35
    /**
36
     * Resolve coordinates.
37
     * @param  Image $image The source image.
38
     * @return int[] The resolved coordinates.
39
     */
40
    public function getCoordinates(Image $image)
41
    {
42
        $coordinates = explode(',', $this->crop);
43
44
        if (count($coordinates) !== 4 or
45
            (!is_numeric($coordinates[0])) or
46
            (!is_numeric($coordinates[1])) or
47
            (!is_numeric($coordinates[2])) or
48
            (!is_numeric($coordinates[3])) or
49
            ($coordinates[0] <= 0) or
50
            ($coordinates[1] <= 0) or
51
            ($coordinates[2] < 0) or
52
            ($coordinates[3] < 0) or
53
            ($coordinates[2] >= $image->width()) or
54
            ($coordinates[3] >= $image->height())) {
55
            return;
56
        }
57
58
        return [
59
            (int) $coordinates[0],
60
            (int) $coordinates[1],
61
            (int) $coordinates[2],
62
            (int) $coordinates[3],
63
        ];
64
    }
65
66
    /**
67
     * Limit coordinates to image boundaries.
68
     * @param  Image $image       The source image.
69
     * @param  int[] $coordinates The coordinates.
70
     * @return int[] The limited coordinates.
71
     */
72
    public function limitToImageBoundaries(Image $image, array $coordinates)
73
    {
74
        if ($coordinates[0] > ($image->width() - $coordinates[2])) {
75
            $coordinates[0] = $image->width() - $coordinates[2];
76
        }
77
78
        if ($coordinates[1] > ($image->height() - $coordinates[3])) {
79
            $coordinates[1] = $image->height() - $coordinates[3];
80
        }
81
82
        return $coordinates;
83
    }
84
}
85