Passed
Push — master ( 5e67b7...45b155 )
by Brent
04:41 queued 02:26
created

FileSizeScaler::scale()   C

Complexity

Conditions 7
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 15
nc 2
nop 2
1
<?php
2
3
namespace Brendt\Image\Scaler;
4
5
use Intervention\Image\Image;
6
use Symfony\Component\Finder\SplFileInfo;
7
8
class FileSizeScaler extends AbstractScaler
9
{
10
11
    /**
12
     * @param SplFileInfo $sourceFile
13
     * @param Image       $imageObject
14
     *
15
     * @return array
16
     */
17
    public function scale(SplFileInfo $sourceFile, Image $imageObject) : array {
18
        $fileSize = $sourceFile->getSize();
19
        $width = $imageObject->getWidth();
20
        $height = $imageObject->getHeight();
21
        $ratio = $height / $width;
22
        $area = $width * $width * $ratio;
23
        $pixelPrice = $fileSize / $area;
24
25
        $sizes = [];
26
27
        do {
28
            // Magic formula.
29
            $newWidth = floor(sqrt(($fileSize / $pixelPrice) / $ratio));
30
31
            if ((!$this->maxFileSize || $fileSize <= $this->maxFileSize) && (!$this->maxWidth || $newWidth <= $this->maxWidth)) {
32
                $sizes[(int) $newWidth] = (int) $newWidth * $ratio;
33
            }
34
35
            $fileSize = $fileSize * $this->stepModifier;
36
        } while ($fileSize > $this->minFileSize && $newWidth > $this->minWidth);
37
38
        return $sizes;
39
    }
40
}
41