Passed
Push — master ( f38dde...147718 )
by Fran
02:30
created

CssTrait::compileCss()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.3329

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 18
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 24
ccs 12
cts 18
cp 0.6667
crap 7.3329
rs 9.0444
1
<?php
2
namespace PSFS\base\extension\traits;
3
4
use MatthiasMullie\Minify\CSS;
5
use PSFS\base\exception\ConfigException;
6
use PSFS\base\Logger;
7
use PSFS\base\types\helpers\AssetsHelper;
8
use PSFS\base\types\helpers\GeneratorHelper;
9
10
/**
11
 * Trait CssTrait
12
 * @package PSFS\base\extension\traits
13
 */
14
trait CssTrait {
15
    /**
16
     * @var string
17
     */
18
    protected $path;
19
20
    /**
21
     * @param string $basePath
22
     * @param string $hash
23
     * @param bool $debug
24
     * @return $this
25
     * @throws \PSFS\base\exception\GeneratorException
26
     */
27 1
    protected function compileCss($basePath, $hash, $debug = false)
28
    {
29 1
        $base = $basePath . "css" . DIRECTORY_SEPARATOR;
30 1
        if ($debug || !file_exists($base . $hash . ".css")) {
31 1
            $data = '';
32 1
            if (0 < count($this->files)) {
33 1
                $minifier = new CSS();
34 1
                foreach ($this->files as $file) {
35 1
                    $data = $this->processCssLine($file, $base, $data);
36
                }
37
            }
38 1
            if($debug) {
39 1
                $this->storeContents($base . $hash . ".css", $data);
0 ignored issues
show
Bug introduced by
It seems like storeContents() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

39
                $this->/** @scrutinizer ignore-call */ 
40
                       storeContents($base . $hash . ".css", $data);
Loading history...
40
            } else {
41
                $minifier = new CSS();
42
                $minifier->add($data);
43
                ini_set('max_execution_time', -1);
44
                ini_set('memory_limit', -1);
45
                GeneratorHelper::createDir($base);
46
                $minifier->minify($base . $hash . ".css");
47
            }
48 1
            unset($minifier);
49
        }
50 1
        return $this;
51
    }
52
53
    /**
54
     * Método que procesa cada línea de la hoja de estilos para copiar los recursos asociados
55
     * @param string $file
56
     * @param string $base
57
     * @param string $data
58
     * @return false|string
59
     * @throws \PSFS\base\exception\GeneratorException
60
     */
61 1
    protected function processCssLine($file, $base, $data)
62
    {
63 1
        if (file_exists($file)) {
64 1
            $pathParts = explode("/", $file);
65 1
            $filePath = $this->hash . "_" . $pathParts[count($pathParts) - 1];
66 1
            if (!file_exists($base . $filePath) || filemtime($base . $filePath) < filemtime($file) || $this->debug) {
67
                //Si tenemos modificaciones tenemos que compilar de nuevo todos los ficheros modificados
68 1
                if (file_exists($base . $this->hash . ".css") && @unlink($base . $this->hash . ".css") === false) {
69
                    throw new ConfigException("Can't unlink file " . $base . $this->hash . ".css");
70
                }
71 1
                $this->loopCssLines($file);
72
            }
73 1
            if ($this->debug) {
74 1
                $data = file_get_contents($file);
75 1
                $this->storeContents($base . $filePath, $data);
76
            } else {
77
                $data .= file_get_contents($file);
78
            }
79 1
            $this->compiled_files[] = "/css/" . $filePath;
0 ignored issues
show
Bug Best Practice introduced by
The property compiled_files does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
80
        }
81
82 1
        return $data;
83
    }
84
85
    /**
86
     * @param string $file
87
     */
88 1
    protected function loopCssLines($file)
89
    {
90 1
        $handle = @fopen($file, 'r');
91 1
        if ($handle) {
0 ignored issues
show
introduced by
$handle is of type false|resource, thus it always evaluated to false.
Loading history...
92 1
            while (!feof($handle)) {
93 1
                $line = fgets($handle);
94 1
                $urls = array();
95 1
                if (preg_match_all('#url\((.*?)\)#', $line, $urls, PREG_SET_ORDER)) {
96 1
                    foreach ($urls as $source) {
97 1
                        $this->extractCssResources($source, $file);
98
                    }
99
                }
100
            }
101 1
            fclose($handle);
102
        }
103 1
    }
104
105
    /**
106
     * @param string $source
107
     * @param string $file
108
     */
109 1
    protected function extractCssResources($source, $file)
110
    {
111 1
        $sourceFile = AssetsHelper::extractSourceFilename($source);
112 1
        $orig = realpath(dirname($file) . DIRECTORY_SEPARATOR . $sourceFile);
113 1
        $origPart = preg_split('/(\/|\\\)public(\/|\\\)/i', $orig);
114
        try {
115 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

115
            if (count($source) > 1 && array_key_exists(1, /** @scrutinizer ignore-type */ $origPart)) {
Loading history...
Bug introduced by
$source of type string is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

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

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