FileResize::execute()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 12
c 2
b 1
f 0
dl 0
loc 17
rs 9.5555
cc 5
nc 4
nop 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: floor12
5
 * Date: 08.07.2018
6
 * Time: 18:41
7
 */
8
9
namespace floor12\files\logic;
10
11
use floor12\files\components\SimpleImage;
12
use floor12\files\models\File;
13
use floor12\files\models\FileType;
14
use yii\base\ErrorException;
15
16
class FileResize
17
{
18
    private $_file;
19
    private $_maxWidth;
20
    private $_maxHeight;
21
    private $_compression;
22
    private $_imageType = IMAGETYPE_JPEG;
23
24
    /**
25
     * FileResize constructor.
26
     * @param File $file Модель файла
27
     * @param int $maxWidth максимальная ширина
28
     * @param int $maxHeight максимальная высота
29
     * @param int $compression качество jpeg
30
     * @throws ErrorException
31
     */
32
    public function __construct(File $file, int $maxWidth, int $maxHeight, $compression = 60)
33
    {
34
        $this->_file = $file;
35
36
        if ($this->_file->type != FileType::IMAGE)
37
            throw new ErrorException('This file is not an image.');
38
39
        if (!file_exists($this->_file->rootPath))
40
            throw new ErrorException('File not found on disk');
41
42
        $this->_maxHeight = $maxHeight;
43
        $this->_maxWidth = $maxWidth;
44
        $this->_compression = $compression;
45
46
    }
47
48
49
    /** Непосредственная обработка
50
     * @return bool
51
     * @throws ErrorException
52
     */
53
    public function execute(): bool
54
    {
55
        if ($this->_file->content_type == 'image/svg+xml')
56
            return true;
57
58
        $image = new SimpleImage();
59
        $image->load($this->_file->rootPath);
60
61
        if ($image->getWidth() > $this->_maxWidth || $image->getHeight() > $this->_maxHeight) {
62
            $image->resizeToWidth($this->_maxWidth);
63
            if ($this->_file->content_type == 'image/png')
64
                $this->_imageType = IMAGETYPE_PNG;
65
            $image->save($this->_file->rootPath, $this->_imageType, $this->_compression);
66
            $this->_file->size = filesize($this->_file->rootPath);
67
            return $this->_file->save(false, ['size']);
68
        }
69
        return true;
70
    }
71
72
}
73