Passed
Push — master ( 5fae1c...f113c6 )
by Fran
10:43 queued 08:12
created

CssTrait::printCss()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

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

117
        $sourceFile = AssetsHelper::extractSourceFilename(/** @scrutinizer ignore-type */ $source);
Loading history...
118 1
        $orig = realpath(dirname($file) . DIRECTORY_SEPARATOR . $sourceFile);
119 1
        $origPart = preg_split('/(\/|\\\)public(\/|\\\)/i', $orig);
120
        try {
121 1
            if (count($source) > 1 && array_key_exists(1, $origPart)) {
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type string; however, parameter $value 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

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