DimensionsRule::validateMediaItem()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 23
rs 8.8333
1
<?php
2
3
namespace Spatie\MediaLibraryPro\Rules\ItemRules;
4
5
class DimensionsRule extends MediaItemRule
6
{
7
    public function __construct(
8
        protected int $requiredWidth = 0,
9
        protected int $requiredHeight = 0
10
    ) {
11
    }
12
13
    public function validateMediaItem(): bool
14
    {
15
        if (! $media = $this->getTemporaryUploadMedia()) {
16
            return true;
17
        }
18
19
        $size = getimagesize($media->getPath());
20
        $actualWidth = $size[0];
21
        $actualHeight = $size[1];
22
23
        if ($this->requiredWidth && $this->requiredHeight) {
24
            return $actualWidth === $this->requiredWidth && $actualHeight === $this->requiredHeight;
25
        }
26
27
        if ($this->requiredWidth) {
28
            return $actualWidth === $this->requiredWidth;
29
        }
30
31
        if ($this->requiredHeight) {
32
            return $actualHeight === $this->requiredHeight;
33
        }
34
35
        return false;
36
    }
37
38
    public function message()
39
    {
40
        $params = [
41
            'width' => $this->requiredWidth,
42
            'height' => $this->requiredHeight,
43
        ];
44
45
        if ($this->requiredWidth && $this->requiredHeight) {
46
            return __('media-library::validation.incorrect_dimensions.both', $params);
47
        }
48
49
        if ($this->requiredWidth) {
50
            return __('media-library::validation.incorrect_dimensions.width', $params);
51
        }
52
53
        if ($this->requiredHeight) {
54
            return __('media-library::validation.incorrect_dimensions.height', $params);
55
        }
56
    }
57
}
58