Issues (1)

src/File/FileMinifier.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * FileMinifier.php - JS and CSS file minifier
5
 *
6
 * Minify the javascript or css 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 as JsMinifier;
18
use MatthiasMullie\Minify\CSS as CssMinifier;
19
use Exception;
20
21
use function file_get_contents;
22
use function file_put_contents;
23
use function in_array;
24
use function is_file;
25
use function pathinfo;
26
use function trim;
27
28
class FileMinifier
29
{
30
    /**
31
     * @var CssMinifier
32
     */
33
    private $xCssMinifier = null;
34
35
    /**
36
     * @return CssMinifier
37
     */
38
    private function css(): CssMinifier
39
    {
40
        return $this->xCssMinifier ?? $this->xCssMinifier = new CssMinifier();
41
    }
42
43
    /**
44
     * Minify javascript or css code
45
     *
46
     * @param string $sFile The javascript or cess file to be minified
47
     * @param string $sMinFile The minified javascript file
48
     *
49
     * @return bool
50
     */
51
    public function minify(string $sFile, string $sMinFile): bool
52
    {
53
        $sExtension = pathinfo($sFile, PATHINFO_EXTENSION);
54
        if(!in_array($sExtension, ['js', 'css']))
55
        {
56
            return false;
57
        }
58
59
        try
60
        {
61
            $sCode = file_get_contents($sFile);
62
            $sMinCode = trim($sExtension === 'js' ?
0 ignored issues
show
It seems like $sExtension === 'js' ? J...->add($sCode)->minify() can also be of type boolean; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

62
            $sMinCode = trim(/** @scrutinizer ignore-type */ $sExtension === 'js' ?
Loading history...
63
                JsMinifier::minify($sCode) :
64
                $this->css()->add($sCode)->minify());
65
            if($sMinCode === '')
66
            {
67
                return false;
68
            }
69
70
            file_put_contents($sMinFile, $sMinCode);
71
72
            return is_file($sMinFile);
73
        }
74
        catch(Exception $e)
75
        {
76
            return false;
77
        }
78
    }
79
}
80