Passed
Push — master ( 8dcff2...10a865 )
by Fran
03:32
created

Cache::extractDataWithFormat()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 5
nop 2
dl 0
loc 19
ccs 14
cts 14
cp 1
crap 7
rs 8.2222
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\exception\ConfigException;
5
use PSFS\base\types\helpers\GeneratorHelper;
6
use PSFS\base\types\SingletonTrait;
7
8
/**
9
 * Class Cache
10
 * @package PSFS\base
11
 * Gestión de los ficheros de cache
12
 */
13
class Cache
14
{
15
16
    const JSON = 1;
17
    const TEXT = 2;
18
    const GZIP = 3;
19
    const JSONGZ = 4;
20
21
    use SingletonTrait;
22
23
    /**
24
     * Método que guarda un text en un fichero
25
     * @param string $data
26
     * @param string $path
27
     * @param boolean $absolute
28
     * @throws ConfigException
29
     */
30 6
    private function saveTextToFile($data, $path, $absolute = false)
31
    {
32 6
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
33 6
        $filename = basename($absolutePath);
34 6
        GeneratorHelper::createDir(str_replace($filename, "", $absolutePath));
35 6
        if (false === file_put_contents($absolutePath, $data)) {
36
            throw new ConfigException(_('No se tienen los permisos suficientes para escribir en el fichero ')
37
                . $absolutePath);
38
        }
39 6
    }
40
41
    /**
42
     * Método que extrae el texto de un fichero
43
     * @param string $path
44
     * @param int $transform
45
     * @param boolean $absolute
46
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array|string|null.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
47
     */
48 7
    public function getDataFromFile($path, $transform = Cache::TEXT, $absolute = false)
49
    {
50 7
        $data = null;
51 7
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
52 7
        if (file_exists($absolutePath)) {
53 5
            $data = file_get_contents($absolutePath);
54 5
        }
55 7
        return Cache::extractDataWithFormat($data, $transform);
56
    }
57
58
    /**
59
     * Método que verifica si un fichero tiene la cache expirada
60
     * @param string $path
61
     * @param int $expires
62
     * @param boolean $absolute
63
     * @return bool
64
     */
65 1
    private function hasExpiredCache($path, $expires = 300, $absolute = false)
66
    {
67 1
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
68 1
        $lasModificationDate = filemtime($absolutePath);
69 1
        return ($lasModificationDate + $expires <= time());
70
    }
71
72
    /**
73
     * Método que transforma los datos de salida
74
     * @param string $data
75
     * @param int $transform
76
     * @return array|string|null
77
     */
78 7
    public static function extractDataWithFormat($data, $transform = Cache::TEXT)
79
    {
80
        switch ($transform) {
81 7
            case Cache::JSON:
82 7
                $data = json_decode($data, true);
83 7
                break;
84 3
            case Cache::JSONGZ:
85 3
                $data = Cache::extractDataWithFormat($data, Cache::GZIP);
86 3
                $data = Cache::extractDataWithFormat($data, Cache::JSON);
87 3
                break;
88 3
            case Cache::GZIP:
89
                // TODO implementar
90 3
                if (function_exists('gzuncompress') && !empty($data)) {
91 1
                    $data = @gzuncompress($data ?: '');
92 1
                }
93 3
                break;
94
        }
95 7
        return $data;
96
    }
97
98
    /**
99
     * Método que transforma los datos de entrada del fichero
100
     * @param string $data
101
     * @param int $transform
102
     * @return string
103
     */
104 6
    public static function transformData($data, $transform = Cache::TEXT)
105
    {
106
        switch ($transform) {
107 6
            case Cache::JSON:
108 6
                $data = json_encode($data, JSON_PRETTY_PRINT);
109 6
                break;
110 2
            case Cache::JSONGZ:
111 1
                $data = Cache::transformData($data, Cache::JSON);
112 1
                $data = Cache::transformData($data, Cache::GZIP);
113 1
                break;
114 2
            case Cache::GZIP:
115 1
                if (function_exists('gzcompress')) {
116 1
                    $data = gzcompress($data ?: '');
117 1
                }
118 1
                break;
119
        }
120 6
        return $data;
121
    }
122
123
    /**
124
     * Método que guarda en fichero los datos pasados
125
     * @param $path
126
     * @param $data
127
     * @param int $transform
128
     * @param boolean $absolutePath
129
     */
130 6
    public function storeData($path, $data, $transform = Cache::TEXT, $absolutePath = false)
131
    {
132 6
        $data = Cache::transformData($data, $transform);
133 6
        $this->saveTextToFile($data, $path, $absolutePath);
134 6
    }
135
136
    /**
137
     * Método que verifica si tiene que leer o no un fichero de cache
138
     * @param string $path
139
     * @param int $expires
140
     * @param callable $function
141
     * @param int $transform
142
     * @return mixed
143
     */
144 1
    public function readFromCache($path, $expires = 300, callable $function, $transform = Cache::TEXT)
145
    {
146 1
        $data = null;
147 1
        if (file_exists(CACHE_DIR . DIRECTORY_SEPARATOR . $path)) {
148 1
            if (null !== $function && $this->hasExpiredCache($path, $expires)) {
149 1
                $data = call_user_func($function);
150 1
                $this->storeData($path, $data, $transform);
151 1
            } else {
152 1
                $data = $this->getDataFromFile($path, $transform);
153
            }
154 1
        }
155 1
        return $data;
156
    }
157
158
    /**
159
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
160
     */
161 1
    private static function checkAdminSite()
162
    {
163 1
        $isAdminRequest = false;
164 1
        $lastRequest = Security::getInstance()->getSessionKey("lastRequest");
165 1
        if (null !== $lastRequest) {
166
            $url = str_replace(Request::getInstance()->getRootUrl(true), '', $lastRequest['url']);
167
            $isAdminRequest = preg_match('/^\/admin\//i', $url);
168
        }
169 1
        return $isAdminRequest;
170
    }
171
172
    /**
173
     * Método estático que revisa si se necesita cachear la respuesta de un servicio o no
174
     * @return integer|boolean
175
     */
176 1
    public static function needCache()
177
    {
178 1
        $needCache = false;
179 1
        if (!self::checkAdminSite()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::checkAdminSite() of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
180 1
            $action = Security::getInstance()->getSessionKey("__CACHE__");
181 1
            if (null !== $action && array_key_exists("cache", $action) && $action["cache"] > 0) {
182 1
                $needCache = $action["cache"];
183 1
            }
184 1
        }
185 1
        return $needCache;
186
    }
187
188
    /**
189
     * Método que construye un hash para almacenar la cache
190
     * @return string
191
     */
192 1
    public function getRequestCacheHash()
193
    {
194 1
        $hash = "";
195 1
        $action = Security::getInstance()->getSessionKey("__CACHE__");
196 1
        if (null !== $action && $action["cache"] > 0) {
197 1
            $hash = $action["http"] . " " . $action["slug"];
198 1
        }
199 1
        return sha1($hash);
200
    }
201
}
202