Test Failed
Pull Request — master (#1)
by
unknown
38:28
created

MinifyComponent::checkS3Path()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 3
1
<?php
2
/**
3
 * Minify.php
4
 * @author Revin Roman
5
 * @link https://processfast.com
6
 */
7
8
namespace processfast\yii\minify\components;
9
10
use processfast\yii\minify\View;
11
12
13
/**
14
 * Class MinifyComponent
15
 * @package processfast\yii\minify\components
16
 */
17
abstract class MinifyComponent
18
{
19
20
    /**
21
     * @var View
22
     */
23
    protected $view;
24
25
    /**
26
     * MinifyComponent constructor.
27
     * @param View $view
28
     */
29
    public function __construct(View $view)
30
    {
31
        $this->view = $view;
32
    }
33
34
    abstract public function export();
35
36
    /**
37
     * @param string $file
38
     * @return string
39
     */
40
    protected function getAbsoluteFilePath($file)
41
    {
42
        return \Yii::getAlias($this->view->basePath) . str_replace(\Yii::getAlias($this->view->webPath), '', $this->cleanFileName($file));
43
    }
44
45
    /**
46
     * @param string $file
47
     * @return string
48
     */
49
    protected function cleanFileName($file)
50
    {
51
        return (strpos($file, '?'))
52
            ? parse_url($file, PHP_URL_PATH)
53
            : $file;
54
    }
55
56
    /**
57
     * @param string $file
58
     * @param string $html
59
     * @return bool
60
     */
61
    protected function thisFileNeedMinify($file, $html)
62
    {
63
        return !$this->isUrl($file, false)
64
        && !$this->isContainsConditionalComment($html)
65
        && !$this->isExcludedFile($file);
66
    }
67
68
    /**
69
     * @param string $url
70
     * @param boolean $checkSlash
71
     * @return bool
72
     */
73
    protected function isUrl($url, $checkSlash = true)
74
    {
75
        $schemas = array_map(function ($val) {
76
            return str_replace('/', '\/', $val);
77
        }, $this->view->schemas);
78
79
        $regexp = '#^(' . implode('|', $schemas) . ')#is';
80
        if ($checkSlash) {
81
            $regexp = '#^(/|\\\\|' . implode('|', $schemas) . ')#is';
82
        }
83
84
        return (bool)preg_match($regexp, $url);
85
    }
86
87
    /**
88
     * @param string $string
89
     * @return bool
90
     */
91
    protected function isContainsConditionalComment($string)
92
    {
93
        return strpos($string, '<![endif]-->') !== false;
94
    }
95
96
    /**
97
     * @param string $file
98
     * @return bool
99
     */
100
    protected function isExcludedFile($file)
101
    {
102
        $result = false;
103
104
        if (!empty($this->view->excludeFiles)) {
105
            foreach ((array)$this->view->excludeFiles as $excludedFile) {
106
                $reg = sprintf('!%s!i', $excludedFile);
107
108
                if (preg_match($reg, $file)) {
109
                    $result = true;
110
                    break;
111
                }
112
            }
113
        }
114
115
        return $result;
116
    }
117
118
    /**
119
     * @param string $resultFile
120
     * @return string
121
     */
122
    protected function prepareResultFile($resultFile)
123
    {
124
        if( !$this->view->S3Upload )
125
        {
126
            $file = sprintf('%s%s', \Yii::getAlias($this->view->webPath), str_replace(\Yii::getAlias($this->view->basePath), '', $resultFile));
127
        }
128
        else
129
        {
130
            $file = $resultFile ;
131
        }
132
133
        $AssetManager = $this->view->getAssetManager();
134
135
        if ($AssetManager->appendTimestamp && ($timestamp = @filemtime($resultFile)) > 0) {
136
            $file .= "?v=$timestamp";
137
        }
138
139
        return $file;
140
    }
141
142
    /**
143
     * @param array $files
144
     * @return string
145
     */
146
    protected function _getSummaryFilesHash($files)
147
    {
148
        $result = '';
149
        foreach ($files as $file => $html) {
150
            $path = $this->getAbsoluteFilePath($file);
151
152
153
            if( $this->view->modifyPath )
154
            {
155
                $modifyPathData = $this->view->modifyPathData ;
156
                if( strpos( $path , $modifyPathData ) !== false )
157
                {
158
                    $path = str_replace( $modifyPathData , '' , $path );
159
                }
160
            }
161
162
            if ($this->thisFileNeedMinify($file, $html) && file_exists($path)) {
163
                switch ($this->view->fileCheckAlgorithm) {
164
                    default:
165
                    case 'filemtime':
166
                        $result .= filemtime($path) . $file;
167
                        break;
168
                    case 'sha1':
169
                        $result .= sha1_file($path);
170
                        break;
171
                }
172
            }
173
        }
174
175
        return sha1($result);
176
    }
177
178
    protected function uploadToS3( $resultFile , $type , $hash )
179
    {
180
        $fileName = $this->getFileInfo( $resultFile , $type , $hash , "FILENAME" );
181
        $mime_type = $this->getFileInfo( $resultFile , $type , $hash , "MIMETYPE" );
182
        $file = $this->handleAssetUpload( $resultFile , $mime_type , $fileName );
183
        return $file;
184
    }
185
186
    protected function getS3Path( $resultFile , $type , $hash )
187
    {
188
        $fileName = $this->getFileInfo( $resultFile , $type , $hash , "FILENAME" );
189
        $mime_type = $this->getFileInfo( $resultFile , $type , $hash , "MIMETYPE" );
0 ignored issues
show
Unused Code introduced by
$mime_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
190
        $bucket = $this->view->awsBucket;
191
        return $this->s3Path( $bucket , $fileName );
192
    }
193
194
    protected function handleAssetUpload($temp, $type, $fileName, $acl = "public-read", $storageClass = "STANDARD")
195
    {
196
        $aws = \Yii::$app->awssdk->getAwsSdk();
197
        $s3 = $aws->createS3();
198
        $bucket = $this->view->awsBucket;
199
        $contentEncoding = "gzip" ;
200
201
        try
202
        {
203
            $result = $s3->putObject(array(
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
204
                'Bucket' => $bucket,
205
                'Key' => $fileName,
206
                'SourceFile' => $temp,
207
                'ContentType' => $type,
208
                'ContentEncoding'=>$contentEncoding,
209
                'ACL' => $acl,
210
                'StorageClass' => $storageClass
211
            ));
212
        }
213
        catch (Exception $e)
0 ignored issues
show
Bug introduced by
The class processfast\yii\minify\components\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
214
        {
215
            throw new HttpException(431, 'Image upload failed to bucket.');
216
        }
217
218
        return $this->s3Path( $bucket , $fileName );
219
    }
220
221
    protected function getVersionName()
222
    {
223
        $sql = 'SELECT current_version FROM `application_version`' ;
224
        $version = \Yii::$app->db->createCommand( $sql )->queryScalar();
225
        return $version;
226
    }
227
228
    protected function s3Path( $bucket , $fileName )
229
    {
230
        return "https://s3.amazonaws.com/".$bucket."/".$fileName;
231
    }
232
233
    protected function checkS3Path( $fileName , $resultFile , $type  )
234
    {
235
        $aws = \Yii::$app->awssdk->getAwsSdk();
236
        $s3 = $aws->createS3();
237
        $bucket = $this->view->awsBucket;
238
239
        if( $s3->doesObjectExist( $bucket , $fileName ) )
240
        {
241
            return $this->s3Path( $bucket , $fileName );
242
        }
243
        else
244
        {
245
            return $this->handleAssetUpload( $resultFile , $type ,$fileName );
246
        }
247
    }
248
249
    protected function doesObjectExist(  $resultFile , $type , $hash )
250
    {
251
        $fileName = $this->getFileInfo( $resultFile , $type , $hash , "FILENAME" );
252
        $mime_type = $this->getFileInfo( $resultFile , $type , $hash , "MIMETYPE" );
0 ignored issues
show
Unused Code introduced by
$mime_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
253
254
        $aws = \Yii::$app->awssdk->getAwsSdk();
255
        $s3 = $aws->createS3();
256
        $bucket = $this->view->awsBucket;
257
258
        return $s3->doesObjectExist( $bucket , $fileName );
259
    }
260
261
    protected function getFileInfo(  $resultFile , $type , $hash  , $typeIn = "FILENAME" )
0 ignored issues
show
Unused Code introduced by
The parameter $resultFile is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
262
    {
263
        $versionName = self::getVersionName() ;
264
265
        $env = "" ;
266
        if( YII_ENV == 'dev' )
267
        {
268
            $env = "dev" ;
269
        }
270
        else if( YII_ENV == 'qa'  )
271
        {
272
            $env = "qa" ;
273
        }
274
        else if( YII_ENV == 'prod'  )
275
        {
276
            $env = "prod" ;
277
        }
278
279
        $mime_type = null ;
280
        $fileName =  null ;
281
        if( $type == "CSS" )
282
        {
283
            $prefix = "" ;
284
            $layout = \Yii::$app->controller->layout ;
285
            if( in_array( $layout , ["old_main","public_pages"] ) )
286
            {
287
                $prefix = "public-pages-" ;
288
            }
289
290
            $mime_type = "text/css" ;
291
            $fileName = "web-assets/".$env."/minify/".$prefix."all-in-one".$versionName."-".$hash.".css";
292
        }
293
        else if( $type == "JS" )
294
        {
295
            $mime_type = "application/javascript" ;
296
            $fileName = "web-assets/".$env."/minify/all-in-one".$versionName."-".$hash.".js";
297
        }
298
299
        if( $typeIn == "FILENAME" )
300
        {
301
            return $fileName;
302
        }
303
        else if( $typeIn == "MIMETYPE" )
304
        {
305
            return $mime_type;
306
        }
307
    }
308
309
}
310