1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Brendt\Image\Scaler; |
4
|
|
|
|
5
|
|
|
use Brendt\Image\ResponsiveImage; |
6
|
|
|
use Intervention\Image\Image; |
7
|
|
|
use Symfony\Component\Finder\Finder; |
8
|
|
|
use Symfony\Component\Finder\SplFileInfo; |
9
|
|
|
|
10
|
|
|
class FileSizeScaler extends AbstractScaler |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @param ResponsiveImage $responsiveImage |
15
|
|
|
* @param Image $imageObject |
16
|
|
|
* |
17
|
|
|
* @return ResponsiveImage |
18
|
|
|
*/ |
19
|
|
|
public function scale(ResponsiveImage $responsiveImage, Image $imageObject) { |
20
|
|
|
$fileName = $responsiveImage->getFileName(); |
21
|
|
|
$extension = $responsiveImage->getExtension(); |
22
|
|
|
$urlPath = $responsiveImage->getUrlPath(); |
23
|
|
|
|
24
|
|
|
$sourceFile = $this->getImageFile($this->sourcePath, $responsiveImage->src()); |
25
|
|
|
|
26
|
|
|
$fileSize = $sourceFile->getSize(); |
27
|
|
|
$width = $imageObject->getWidth(); |
28
|
|
|
$height = $imageObject->getHeight(); |
29
|
|
|
$ratio = $height / $width; |
30
|
|
|
$area = $width * $width * $ratio; |
31
|
|
|
$pixelPrice = $fileSize / $area; |
32
|
|
|
|
33
|
|
|
// Magic formula. |
34
|
|
|
$newWidth = floor(sqrt(($fileSize / $pixelPrice) / $ratio)); |
35
|
|
|
while ($fileSize > $this->minFileSize && $newWidth > $this->minWidth) { |
36
|
|
|
$scaledName = "{$fileName}-{$newWidth}.{$extension}"; |
37
|
|
|
$scaledSrc = "{$urlPath}/{$scaledName}"; |
38
|
|
|
$responsiveImage->addSource($scaledSrc, $newWidth); |
39
|
|
|
|
40
|
|
|
$publicScaledPath = "{$this->publicPath}/{$urlPath}/{$scaledName}"; |
41
|
|
View Code Duplication |
if (!$this->enableCache || !$this->fs->exists($publicScaledPath)) { |
|
|
|
|
42
|
|
|
$this->fs->dumpFile( |
43
|
|
|
$publicScaledPath, |
44
|
|
|
$imageObject->resize($newWidth, $newWidth * $ratio)->encode($extension) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$fileSize = $fileSize * $this->stepModifier; |
49
|
|
|
$newWidth = floor(sqrt(($fileSize / $pixelPrice) / $ratio)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $responsiveImage; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $directory |
57
|
|
|
* @param string $path |
58
|
|
|
* |
59
|
|
|
* @return SplFileInfo |
60
|
|
|
*/ |
61
|
|
|
private function getImageFile($directory, $path) { |
62
|
|
|
$iterator = Finder::create()->files()->in($directory)->path(ltrim($path, '/'))->getIterator(); |
63
|
|
|
$iterator->rewind(); |
64
|
|
|
|
65
|
|
|
return $iterator->current(); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
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.