Completed
Push — master ( 7a337d...053d9e )
by Vladimir
01:53
created

TinifyController   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 158
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 20
dl 0
loc 158
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 9 2
A actionCount() 0 7 1
C actionCompressCatalog() 0 49 9
B actionCompress() 0 33 5
A actionTestConnect() 0 14 3
1
<?php
2
/**
3
 * @link https://github.com/Vintage-web-production/yii2-tinify
4
 * @copyright Copyright (c) 2017 Vintage Web Production
5
 * @license BSD 3-Clause License
6
 */
7
8
namespace vintage\tinify\cli;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\console\Controller;
13
use yii\helpers\Console;
14
use yii\helpers\StringHelper;
15
use Tinify\Tinify;
16
use Tinify\AccountException;
17
use Tinify\Source;
18
use vintage\tinify\helpers\TinifyData;
19
20
/**
21
 * CLI with features for Tinify.
22
 *
23
 * @author Vladimir Kuprienko <[email protected]>
24
 * @since 1.0
25
 */
26
class TinifyController extends Controller
27
{
28
    /**
29
     * @var null|string
30
     */
31
    protected $_apiToken = null;
32
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public function init()
38
    {
39
        $paramToken = TinifyData::getApiToken();
40
41
        if ($paramToken === null) {
42
            throw new InvalidConfigException('You should to set API token');
43
        }
44
45
        Tinify::setKey($paramToken);
46
    }
47
48
    /**
49
     * Check API work status.
50
     *
51
     * @param null|string $token
52
     * @return int
53
     * @throws InvalidConfigException
54
     */
55
    public function actionTestConnect($token = null)
56
    {
57
        if ($token !== null) {
58
            Tinify::setKey($token);
59
        }
60
61
        try {
62
            \Tinify\validate();
63
            $this->stdout("Connected successfully!\n", Console::FG_GREEN);
64
        } catch (AccountException $ex) {
65
            $this->stdout("Wrong API token!\n", Console::FG_RED);
66
        }
67
68
        return self::EXIT_CODE_NORMAL;
69
    }
70
71
    /**
72
     * Compress image.
73
     *
74
     * @param string $src Path to source image.
75
     * @param string $dest Path for destination image.
76
     * @return int
77
     * @throws \Exception
78
     */
79
    public function actionCompress($src, $dest)
80
    {
81
        $isURL = true;
82
        if (!preg_match('/^(http|https):\/\/[a-zA-Z0-9\.-\/]+.(jpg|png)$/', $src)) {
83
            $isURL = false;
84
85
            $src = Yii::getAlias($src);
86
            if (!file_exists($src)) {
87
                throw new \Exception('Source file not found!');
88
            }
89
90
            $fileSize = filesize($src);
91
            $this->stdout("Before compressing size: $fileSize bytes\n", Console::FG_GREEN);
92
        }
93
94
        $dest = Yii::getAlias($dest);
95
        $this->stdout("Compressing...\n", Console::FG_GREEN);
96
97
        try {
98
            if (!$isURL) {
99
                $source = Source::fromFile($src);
100
            } else {
101
                $source = Source::fromUrl($src);
102
            }
103
            $source->toFile($dest);
104
        } catch (\Exception $ex) {
105
            throw $ex;
106
        }
107
108
        $fileSize = filesize($dest);
109
        $this->stdout("After compressing size: $fileSize bytes\n", Console::FG_GREEN);
110
111
        return self::EXIT_CODE_NORMAL;
112
    }
113
114
    /**
115
     * Compress images in catalog.
116
     * Old images will be moved to catalog with name "old".
117
     *
118
     * @param string $path Path to images files.
119
     * @throws \Exception
120
     */
121
    public function actionCompressCatalog($path)
122
    {
123
        $this->stdout("Start...\n", Console::FG_YELLOW);
124
125
        $oldCatalogName = 'old';
126
        $oldCatalogPath = Yii::getAlias($path . '/' . $oldCatalogName);
127
        if (!file_exists($oldCatalogPath)) {
128
            mkdir($oldCatalogPath);
129
        }
130
131
        $files = scandir(Yii::getAlias($path));
132
133
        $filesToCompressCount = 0;
134
        $filesToCompress = [];
135
        foreach ($files as $file) {
136
            $filePath = Yii::getAlias($path . DIRECTORY_SEPARATOR . $file);
137
            if (
138
                (is_file($filePath)
139
                && file_exists($filePath))
140
                && TinifyData::allowCompression($filePath)
141
            ) {
142
                $filesToCompressCount++;
143
                $filesToCompress[] = $filePath;
144
            }
145
        }
146
        clearstatcache();
147
        $this->stdout("$filesToCompressCount files to compress...\n", Console::FG_YELLOW);
148
149
        foreach ($filesToCompress as $index => $file) {
150
            try {
151
                $this->stdout('[' . (++$index). "]\t" . $file);
152
                $startTime = microtime(true);
153
154
                $source = Source::fromFile($file);
155
                $oldFile = Yii::getAlias($path . '/' . $oldCatalogName . '/' . StringHelper::basename($file));
156
                rename($file, $oldFile);
157
                if (!$source->toFile($file)) {
158
                    rename($oldFile, $file);
159
                    $this->stdout("[Error]\n", Console::FG_RED);
160
                } else {
161
                    $timeToPrint = sprintf('%.4F sec', microtime(true) - $startTime);
162
                    $this->stdout("\t[Compressed - $timeToPrint]\n", Console::FG_GREEN);
163
                }
164
            } catch (\Exception $ex) {
165
                throw $ex;
166
            }
167
        }
168
169
        $this->stdout("Complete!\n", Console::FG_YELLOW);
170
    }
171
172
    /**
173
     * Display compressed images count.
174
     *
175
     * @return int
176
     */
177
    public function actionCount()
178
    {
179
        \Tinify\validate();
180
        $count = Tinify::getCompressionCount();
181
        $this->stdout("Compressed images: $count\n", Console::FG_GREEN);
182
183
        return self::EXIT_CODE_NORMAL;
184
    }
185
}
186