FileSizeOptimizedWidthCalculator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 51
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A calculateWidthsFromFile() 0 10 1
A calculateWidths() 0 24 3
A finishedCalculating() 0 12 3
1
<?php
2
3
namespace Spatie\MediaLibrary\ResponsiveImages\WidthCalculator;
4
5
use Illuminate\Support\Collection;
6
use Spatie\MediaLibrary\Helpers\ImageFactory;
7
8
class FileSizeOptimizedWidthCalculator implements WidthCalculator
9
{
10
    public function calculateWidthsFromFile(string $imagePath): Collection
11
    {
12
        $image = ImageFactory::load($imagePath);
13
14
        $width = $image->getWidth();
15
        $height = $image->getHeight();
16
        $fileSize = filesize($imagePath);
17
18
        return $this->calculateWidths($fileSize, $width, $height);
19
    }
20
21
    public function calculateWidths(int $fileSize, int $width, int $height): Collection
22
    {
23
        $targetWidths = collect();
24
25
        $targetWidths->push($width);
26
27
        $ratio = $height / $width;
28
        $area = $height * $width;
29
30
        $predictedFileSize = $fileSize;
31
        $pixelPrice = $predictedFileSize / $area;
32
33
        while (true) {
34
            $predictedFileSize *= 0.7;
35
36
            $newWidth = (int) floor(sqrt(($predictedFileSize / $pixelPrice) / $ratio));
37
38
            if ($this->finishedCalculating($predictedFileSize, $newWidth)) {
39
                return $targetWidths;
40
            }
41
42
            $targetWidths->push($newWidth);
43
        }
44
    }
45
46
    protected function finishedCalculating(int $predictedFileSize, int $newWidth): bool
47
    {
48
        if ($newWidth < 20) {
49
            return true;
50
        }
51
52
        if ($predictedFileSize < (1024 * 10)) {
53
            return true;
54
        }
55
56
        return false;
57
    }
58
}
59