Passed
Push — master ( 147718...79af4d )
by Fran
02:42
created

CssTrait::printCss()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

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

115
        $sourceFile = AssetsHelper::extractSourceFilename(/** @scrutinizer ignore-type */ $source);
Loading history...
116 1
        $orig = realpath(dirname($file) . DIRECTORY_SEPARATOR . $sourceFile);
117 1
        $origPart = preg_split('/(\/|\\\)public(\/|\\\)/i', $orig);
118
        try {
119 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

119
            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

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