Passed
Push — master ( 96a485...3c999b )
by Fran
02:49
created

CssTrait::extractCssResources()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 11.9809

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
c 1
b 0
f 0
nc 10
nop 2
dl 0
loc 21
ccs 8
cts 15
cp 0.5333
crap 11.9809
rs 8.8333
1
<?php
2
namespace PSFS\base\extension\traits;
3
4
use MatthiasMullie\Minify\CSS;
5
use PSFS\base\config\Config;
6
use PSFS\base\exception\ConfigException;
7
use PSFS\base\Logger;
8
use PSFS\base\types\helpers\AssetsHelper;
9
use PSFS\base\types\helpers\GeneratorHelper;
10
use PSFS\base\types\helpers\Inspector;
11
12
/**
13
 * Trait CssTrait
14
 * @package PSFS\base\extension\traits
15
 */
16
trait CssTrait {
17
18
    use SRITrait {
19
        getSriHash as getCssSRIHash;
20
    }
21
22
    /**
23
     * @var string
24
     */
25
    protected $path;
26
27
    /**
28
     * @param string $basePath
29
     * @param string $hash
30
     * @param bool $debug
31
     * @return $this
32
     * @throws \PSFS\base\exception\GeneratorException
33
     */
34 1
    protected function compileCss($basePath, $hash)
35
    {
36 1
        $debug = Config::getParam('debug');
37 1
        $base = $basePath . "css" . DIRECTORY_SEPARATOR;
38 1
        if ($debug || !file_exists($base . $hash . ".css")) {
39 1
            $data = '';
40 1
            if (0 < count($this->files)) {
41 1
                $minifier = new CSS();
42 1
                foreach ($this->files as $file) {
43 1
                    $data = $this->processCssLine($file, $base, $data, $hash);
44
                }
45
            }
46 1
            if($debug) {
47 1
                AssetsHelper::storeContents($base . $hash . ".css", $data);
48
            } else {
49
                $minifier = new CSS();
50
                $minifier->add($data);
51
                ini_set('max_execution_time', -1);
52
                ini_set('memory_limit', -1);
53
                GeneratorHelper::createDir($base);
54
                $minifier->minify($base . $hash . ".css");
55
            }
56 1
            unset($minifier);
57
        }
58 1
        return $this;
59
    }
60
61
    /**
62
     * Método que procesa cada línea de la hoja de estilos para copiar los recursos asociados
63
     * @param string $file
64
     * @param string $base
65
     * @param string $data
66
     * @return false|string
67
     * @throws \PSFS\base\exception\GeneratorException
68
     */
69 1
    protected function processCssLine($file, $base, $data, $hash)
70
    {
71 1
        if (file_exists($file)) {
72 1
            $debug = Config::getParam('debug');
73 1
            $pathParts = explode("/", $file);
74 1
            $filePath = $this->hash . "_" . $pathParts[count($pathParts) - 1];
75 1
            if (!file_exists($base . $filePath) || filemtime($base . $filePath) < filemtime($file) || $debug) {
76
                //Si tenemos modificaciones tenemos que compilar de nuevo todos los ficheros modificados
77 1
                if (file_exists($base . $hash . ".css") && @unlink($base . $hash . ".css") === false) {
78
                    throw new ConfigException("Can't unlink file " . $base . $hash . ".css");
79
                }
80 1
                $this->loopCssLines($file);
81
            }
82 1
            if ($debug) {
83 1
                $data = file_get_contents($file);
84 1
                AssetsHelper::storeContents($base . $filePath, $data);
85
            } else {
86
                $data .= file_get_contents($file);
87
            }
88 1
            $this->compiledFiles[] = "/css/" . $filePath;
0 ignored issues
show
Bug Best Practice introduced by
The property compiledFiles does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
89
        }
90
91 1
        return $data;
92
    }
93
94
    /**
95
     * @param string $file
96
     */
97 1
    protected function loopCssLines($file)
98
    {
99 1
        $handle = @fopen($file, 'r');
100 1
        if ($handle) {
0 ignored issues
show
introduced by
$handle is of type false|resource, thus it always evaluated to false.
Loading history...
101 1
            while (!feof($handle)) {
102 1
                $line = fgets($handle);
103 1
                $urls = array();
104 1
                if (preg_match_all('#url\((.*?)\)#', $line, $urls, PREG_SET_ORDER)) {
105 1
                    foreach ($urls as $source) {
106 1
                        $this->extractCssResources($source, $file);
107
                    }
108
                }
109
            }
110 1
            fclose($handle);
111
        }
112 1
    }
113
114
    /**
115
     * @param string|array $source
116
     * @param string $file
117
     */
118 1
    protected function extractCssResources($source, $file)
119
    {
120 1
        Inspector::stats('[CssTrait] Start collecting resources from ' . $file, Inspector::SCOPE_DEBUG);
121 1
        $sourceFile = AssetsHelper::extractSourceFilename($source);
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type array; however, parameter $source of PSFS\base\types\helpers\...extractSourceFilename() 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

121
        $sourceFile = AssetsHelper::extractSourceFilename(/** @scrutinizer ignore-type */ $source);
Loading history...
122 1
        $orig = realpath(dirname($file) . DIRECTORY_SEPARATOR . $sourceFile);
123 1
        $origPart = preg_split('/(\/|\\\)public(\/|\\\)/i', $orig);
124
        try {
125 1
            if (count($source) > 1 && array_key_exists(1, $origPart)) {
0 ignored issues
show
Bug introduced by
It seems like $origPart can also be of type false; however, parameter $search of array_key_exists() does only seem to accept array, 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

125
            if (count($source) > 1 && array_key_exists(1, /** @scrutinizer ignore-type */ $origPart)) {
Loading history...
Bug introduced by
It seems like $source can also be of type string; however, parameter $var of count() does only seem to accept Countable|array, 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

125
            if (count(/** @scrutinizer ignore-type */ $source) > 1 && array_key_exists(1, $origPart)) {
Loading history...
126
                $dest = $this->path . $origPart[1];
127
                GeneratorHelper::createDir(dirname($dest));
128
                if (!file_exists($dest) || filemtime($orig) > filemtime($dest)) {
129
                    if (@copy($orig, $dest) === FALSE) {
130
                        throw new \RuntimeException('Can\' copy ' . $dest . '');
131
                    }
132 1
                    Logger::log("$orig copiado a $dest", LOG_INFO);
133
                }
134
            }
135
        } catch (\Exception $e) {
136
            Logger::log($e->getMessage(), LOG_ERR);
137
        }
138 1
        Inspector::stats('[CssTrait] End collecting resources from ' . $file, Inspector::SCOPE_DEBUG);
139 1
    }
140
141
    /**
142
     * @param array $compiledFiles
143
     * @param string $baseUrl
144
     * @param string $hash
145
     */
146 1
    protected function printCss(array $compiledFiles, $baseUrl, $hash)
147
    {
148 1
        if (Config::getParam('debug') && 0 < count($compiledFiles)) {
149 1
            foreach ($compiledFiles as $file) {
150 1
                echo "\t\t<link href='{$file}' rel='stylesheet' media='screen, print'>";
151
            }
152
        } else {
153 1
            $sri = $this->getCssSRIHash($hash, 'css');
154 1
            echo "\t\t<link href='" . $baseUrl . "/css/" . $hash . ".css' rel='stylesheet' " .
155 1
            "crossorigin='anonymous' integrity='sha384-" . $sri . "'>";
156
        }
157 1
    }
158
}
159