FileMinifier::minifyCode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * FileMinifier.php - JS and CSS file minifier
5
 *
6
 * Minify the javascript code generated by the Jaxon library and plugins.
7
 *
8
 * @package jaxon-utils
9
 * @author Thierry Feuzeu <[email protected]>
10
 * @copyright 2022 Thierry Feuzeu <[email protected]>
11
 * @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
12
 * @link https://github.com/jaxon-php/jaxon-core
13
 */
14
15
namespace Jaxon\Utils\File;
16
17
use JShrink\Minifier;
18
19
use Exception;
20
21
use function file_get_contents;
22
use function file_put_contents;
23
use function is_file;
24
25
class FileMinifier
26
{
27
    /**
28
     * Read the file content
29
     *
30
     * @param string $sPath
31
     *
32
     * @return string|false
33
     */
34
    private function readFile(string $sPath)
35
    {
36
        try
37
        {
38
            return file_get_contents($sPath);
39
        }
40
        catch(Exception $e)
41
        {
42
            return false;
43
        }
44
    }
45
46
    /**
47
     * Read the file content
48
     *
49
     * @param string $sCode
50
     *
51
     * @return string|false
52
     */
53
    private function minifyCode(string $sCode)
54
    {
55
        try
56
        {
57
            return Minifier::minify($sCode);
0 ignored issues
show
Bug Best Practice introduced by
The expression return JShrink\Minifier::minify($sCode) returns the type boolean which is incompatible with the documented return type false|string.
Loading history...
58
        }
59
        catch(Exception $e)
60
        {
61
            return false;
62
        }
63
    }
64
65
    /**
66
     * Minify javascript code
67
     *
68
     * @param string $sJsFile The javascript file to be minified
69
     * @param string $sMinFile The minified javascript file
70
     *
71
     * @return bool
72
     */
73
    public function minify(string $sJsFile, string $sMinFile): bool
74
    {
75
        if(($sJsCode = $this->readFile($sJsFile)) === false ||
76
            ($sMinCode = $this->minifyCode($sJsCode)) === false)
77
        {
78
            return false;
79
        }
80
        file_put_contents($sMinFile, $sMinCode);
81
        return is_file($sMinFile);
82
    }
83
}
84