Completed
Push — master ( 71902b...fdb0db )
by Florin
12:00
created

Minify::getMinifiedFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
1
<?php
2
3
namespace Makehappen\AutoMinifier;
4
5
use MatthiasMullie\Minify as Minifier;
6
7
/**
8
 * Class Minify
9
 * @package Makehappen\AutoMinifier
10
 */
11
class Minify
12
{
13
    /**
14
     * Cache bust file path
15
     *
16
     * @var string
17
     */
18
    protected $strCacheBustFile;
19
20
    /**
21
     * Public folder path
22
     *
23
     * @var string
24
     */
25
    protected $strPublicFolderPath;
26
27
    /**
28
     * File types supported
29
     *
30
     * @var array
31
     */
32
    protected $arrFileTypes;
33
34
    /**
35
     * Destination file extension
36
     *
37
     * @var string
38
     */
39
    protected $strDestinationExtension;
40
41
    /**
42
     * Destination folder
43
     *
44
     * @var
45
     */
46
    protected $strDestinationFolder;
47
48
    /**
49
     * Destination file
50
     *
51
     * @var
52
     */
53
    protected $strDestinationFile;
54
55
    /**
56
     * Set env to dev
57
     *
58
     * @var
59
     */
60
    protected $blnIsDev;
61
62
    /**
63
     * Create a new Minifier Instance
64
     */
65
    public function __construct()
66
    {
67
        // set class variables
68
        $this->init();
69
    }
70
71
    /**
72
     * Set env to Dev
73
     *
74
     * @param bool $bln
75
     * @return $this
76
     */
77
    public function setDev($bln = true)
78
    {
79
        $this->blnIsDev = $bln;
80
        return $this;
81
    }
82
83
    /**
84
     * Set Class Variables
85
     *
86
     * @return null
87
     */
88
    public function init()
89
    {
90
        // set public folder location
91
        $this->setPublicFolder();
92
93
        // set file types we want minified
94
        $this->arrFileTypes = [
95
            'js' => ['js'],
96
            'css' => ['css', 'sass', 'scss']
97
        ];
98
99
        return null;
100
    }
101
102
    /**
103
     * Set Cache bust file
104
     *
105
     * @param string $strFile
106
     * @return $this
107
     */
108
    public function setCacheBustFile($strFile = 'autominifier-cache-bust.txt')
109
    {
110
        $this->strCacheBustFile = $this->strPublicFolderPath . '/' . $this->getDestinationFolder() . "/$strFile";
111
        return $this;
112
    }
113
114
    /**
115
     * Set public folder
116
     *
117
     * @param string $strFolder
118
     * @return $this
119
     */
120
    public function setPublicFolder($strFolder = '/../../../../public')
121
    {
122
        // set application public path relative to package location
123
        $this->strPublicFolderPath = __DIR__ . $strFolder;
124
        return $this;
125
    }
126
127
    /**
128
     * Set test folder
129
     *
130
     * @return $this
131
     */
132
    public function setTest()
133
    {
134
        // set application public path relative to package location
135
        $this->setPublicFolder('/../build');
136
137
        // cache bust file
138
        $this->setCacheBustFile();
139
140
        return $this;
141
    }
142
143
    /**
144
     * Get Public folder
145
     *
146
     * @return string
147
     */
148
    public function getPublicFolder()
149
    {
150
        return $this->strPublicFolderPath;
151
    }
152
153
    /**
154
     * Build minified file
155
     *
156
     * @var $strFolder string
157
     * @var $strFile string
158
     * @return string
159
     */
160
    public function js($strFolder = '/js', $strFile = 'app.min.js')
161
    {
162
        return $this->getMinifiedFile($strType = 'js', $strFolder, $strFile);
163
    }
164
165
    /**
166
     * Build CSS minified file
167
     *
168
     * @var $strFolder string
169
     * @var $strFile string
170
     * @return bool|null|string
171
     */
172
    public function css($strFolder = '/css', $strFile = 'app.min.css')
173
    {
174
        return $this->getMinifiedFile($strType = 'css', $strFolder, $strFile);
175
    }
176
    
177
    /**
178
     * Generate minified file
179
     *
180
     * @param string $strType
181
     * @param string $strFolder
182
     * @param string $strFile
183
     * @return string
184
     */
185
    public function getMinifiedFile($strType = 'css', $strFolder = '/css', $strFile = 'app.min.css')
186
    {
187
        $this->setDestinationExtensionType($strType);
188
        $this->setDestinationFolder($strFolder);
189
        $this->setDestinationFile($strFile);
190
        $this->setCacheBustFile();
191
        return $strFolder . '/' . $strFile .'?' . $this->process();
192
    }
193
194
    /**
195
     * Process Built
196
     *
197
     * @return bool|null|string
198
     */
199
    public function process()
200
    {
201
        // return last cache bust in non development environments
202
        if (!$this->isDevEnv()) {
203
            return $this->getCacheBust();
204
        }
205
206
        // build application file
207
        $strApplicationFileContents = $this->build($this->arrFileTypes[$this->getDestinationExtension()]);
208
209
        // save application file contents
210
        $strApplicationFileContents = $this->createApplicationFile($strApplicationFileContents);
211
212
        // save new cache bust
213
        return $this->saveCacheBust($strApplicationFileContents);
214
    }
215
216
    /**
217
     * Set destination folder
218
     *
219
     * @param $strFolder
220
     * @return $this
221
     */
222
    public function setDestinationFolder($strFolder)
223
    {
224
        $this->strDestinationFolder = $strFolder;
225
        return $this;
226
    }
227
228
    /**
229
     * Set destination file
230
     *
231
     * @param $strFile
232
     * @return $this
233
     */
234
    public function setDestinationFile($strFile)
235
    {
236
        $this->strDestinationFile = $strFile;
237
        return $this;
238
    }
239
240
    /**
241
     * Get destination folder
242
     *
243
     * @return mixed
244
     */
245
    public function getDestinationFolder()
246
    {
247
        return $this->strDestinationFolder;
248
    }
249
250
    /**
251
     * Set destination file
252
     *
253
     * @return mixed
254
     */
255
    public function getDestinationFile()
256
    {
257
        return $this->strDestinationFile;
258
    }
259
260
    /**
261
     * Save Cache Bust
262
     *
263
     * @var string $strApplicationFileContents
264
     * @return null
265
     */
266
    public function saveCacheBust($strApplicationFileContents = '')
267
    {
268
        // get contents signature
269
        $strNewCacheBust = md5($strApplicationFileContents);
270
271
        // get prior cache bust
272
        $strPriorCacheBust = $this->getCacheBust();
273
274
        // if unchanged, stop here
275
        if ($strPriorCacheBust == $strNewCacheBust) {
276
            return $strPriorCacheBust;
277
        }
278
279
        // set new cache bust
280
        file_put_contents($this->strCacheBustFile, $strNewCacheBust);
281
282
        // return new cache bust
283
        return $strNewCacheBust;
284
    }
285
286
    /**
287
     * Get Cache Bust
288
     *
289
     * @return bool|string
290
     */
291
    public function getCacheBust()
292
    {
293
        // abort if file not found
294
        if (!file_exists($this->strCacheBustFile)) {
295
            return '';
296
        }
297
298
        // get cache bust file contents
299
        return file_get_contents($this->strCacheBustFile);
300
    }
301
302
    /**
303
     * Determine if we are in development environment
304
     *
305
     * @return bool
306
     */
307
    public function isDevEnv()
308
    {
309
        // if set to dev stop here
310
        if ($this->blnIsDev) {
311
            return true;
312
        }
313
314
        // domain extension is .dev
315
        if ($this->isDevDomain()) {
316
            return true;
317
        }
318
319
        // localhost
320
        if ($this->isLocalhost()) {
321
            return true;
322
        }
323
324
        return false;
325
    }
326
327
    /**
328
     * Determine if it's .dev domain
329
     *
330
     * @return bool
331
     */
332
    public function isDevDomain()
0 ignored issues
show
Coding Style introduced by
isDevDomain uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
333
    {
334
        $arrDomain = explode('.', $_SERVER['HTTP_HOST']);
335
        return array_pop($arrDomain) == 'dev';
336
    }
337
338
    /**
339
     * Is is localhost
340
     *
341
     * @return bool
342
     */
343
    public function isLocalhost()
0 ignored issues
show
Coding Style introduced by
isLocalhost uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
344
    {
345
        // must have HTTP_HOST set
346
        if (empty($_SERVER['HTTP_HOST'])) {
347
            return false;
348
        }
349
350
        return $_SERVER['HTTP_HOST'] == 'localhost';
351
    }
352
353
    /**
354
     * Create minified and concatenated file
355
     *
356
     * @param $strApplicationFileContents
357
     * @return string
358
     */
359
    public function createApplicationFile($strApplicationFileContents)
360
    {
361
        file_put_contents($this->getAppFileName(), $strApplicationFileContents);
362
        return $strApplicationFileContents;
363
    }
364
365
    /**
366
     * Get application file name
367
     *
368
     * @return string
369
     */
370
    public function getAppFileName()
371
    {
372
        return $this->strPublicFolderPath . $this->getDestinationFolder() . '/' . $this->getDestinationFile();
373
    }
374
375
    /**
376
     * Set destination file extension
377
     *
378
     * @param $strDestinationExtension
379
     */
380
    public function setDestinationExtensionType($strDestinationExtension)
381
    {
382
        $this->strDestinationExtension = $strDestinationExtension;
383
    }
384
385
    /**
386
     * Get destination file type extension
387
     *
388
     * @return mixed
389
     */
390
    public function getDestinationExtension()
391
    {
392
        return $this->strDestinationExtension;
393
    }
394
395
    /**
396
     * Build file
397
     *
398
     * @param $arrOriginExtensions
399
     * @return string
400
     */
401
    public function build($arrOriginExtensions)
402
    {
403
        $strPublicFolder = $this->strPublicFolderPath . '/' . $this->getDestinationFolder();
404
405
        // abort if folder not found
406
        if (!is_dir($strPublicFolder)) {
407
            return $strPublicFolder . ' folder not found';
408
        }
409
410
        // get all files
411
        $arrFiles = scandir($strPublicFolder);
412
413
        // loop through all files
414
        $strMinifiedFileContents = '';
415
        foreach ($arrFiles as $strFileName) {
416
            // get file extension
417
            $arrFileName = explode('.', $strFileName);
418
            $strFileExtension = array_pop($arrFileName);
419
420
            // must be a listed file type
421
            if (!in_array($strFileExtension, $arrOriginExtensions)) {
422
                continue;
423
            }
424
425
            // must not be the app file
426
            if ($strFileName == $this->getDestinationFile()) {
427
                continue;
428
            }
429
430
            // add new minified file to concatenated version
431
            $strMinifiedFileContents .=
432
                "\n/* $strFileName */\n" .
433
                $this->getMinifiedContent($strPublicFolder . '/' . $strFileName)
434
            ;
435
        }
436
437
        // returned concatenated version of minifired files
438
        return $strMinifiedFileContents;
439
    }
440
441
    /**
442
     * Get minified Content
443
     *
444
     * @param $strFile
445
     * @return bool|string
446
     */
447
    public function getMinifiedContent($strFile)
448
    {
449
        // if it's minified already return content
450
        if (preg_match('/\.min\./', $strFile)) {
451
            return file_get_contents($strFile);
452
        }
453
454
        // return minified content
455
        return $this->minifyContent($strFile);
456
    }
457
458
    /**
459
     * Minify content
460
     *
461
     * @param  $strFile
462
     * @return bool|string
463
     */
464
    public function minifyContent($strFile)
465
    {
466
        // minify based on file type
467
        switch ($this->getDestinationExtension()) {
468
            case 'js':
469
                return $this->minifyJs($strFile);
470
            case 'css':
471
                return $this->minifyCss($strFile);
472
            default:
473
                return '';
474
        }
475
    }
476
477
    /**
478
     * Minify JS
479
     *
480
     * @param $strFile
481
     * @return bool|string
482
     */
483
    public function minifyJs($strFile)
484
    {
485
        return (new Minifier\JS($strFile))->minify();
486
    }
487
488
    /**
489
     * Minify CSS
490
     *
491
     * @param $strFile
492
     * @return bool|string
493
     */
494
    public function minifyCss($strFile)
495
    {
496
        return (new Minifier\CSS($strFile))->minify();
497
    }
498
}
499