Completed
Push — master ( c877ec...c350e4 )
by Fran
04:32
created

Cache::transformData()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 3
b 0
f 0
nc 5
nop 2
dl 0
loc 18
ccs 7
cts 8
cp 0.875
crap 5.0488
rs 8.8571
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\exception\ConfigException;
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 2
    private function saveTextToFile($data, $path, $absolute = false)
31
    {
32 2
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
33 2
        $filename = basename($absolutePath);
34 2
        Config::createDir(str_replace($filename, "", $absolutePath));
35 2
        if (false === file_put_contents($absolutePath, $data)) {
36
            throw new ConfigException(_('No se tienen los permisos suficientes para escribir en el fichero ') . $absolutePath);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
37
        }
38 2
    }
39
40
    /**
41
     * Método que extrae el texto de un fichero
42
     * @param string $path
43
     * @param int $transform
44
     * @param boolean $absolute
45
     * @return array|string|null
46
     */
47 2
    public function getDataFromFile($path, $transform = Cache::TEXT, $absolute = false)
48
    {
49 2
        $data = null;
50 2
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
51 2
        if (file_exists($absolutePath)) {
52 2
            $data = file_get_contents($absolutePath);
53 2
        }
54 2
        return Cache::extractDataWithFormat($data, $transform);
55
    }
56
57
    /**
58
     * Método que verifica si un fichero tiene la cache expirada
59
     * @param string $path
60
     * @param int $expires
61
     * @param boolean $absolute
62
     * @return bool
63
     */
64
    private function hasExpiredCache($path, $expires = 300, $absolute = false)
65
    {
66
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
67
        $lasModificationDate = filemtime($absolutePath);
68
        return ($lasModificationDate + $expires <= time());
69
    }
70
71
    /**
72
     * Método que transforma los datos de salida
73
     * @param string $data
74
     * @param int $transform
75
     * @return array|string|null
76
     */
77 2
    public static function extractDataWithFormat($data, $transform = Cache::TEXT)
78
    {
79
        switch ($transform) {
80 2
            case Cache::JSON:
81 2
                $data = json_decode($data, true);
82 2
                break;
83
            case Cache::JSONGZ:
84
                $data = Cache::extractDataWithFormat($data, Cache::GZIP);
85
                $data = Cache::extractDataWithFormat($data, Cache::JSON);
86
                break;
87
            case Cache::GZIP:
88
                // TODO implementar
89
                if(function_exists('gzuncompress')) {
90 2
                    $data = gzuncompress($data);
91
                }
92
                break;
93
        }
94
        return $data;
95
    }
96
97
    /**
98
     * Método que transforma los datos de entrada del fichero
99 2
     * @param string $data
100
     * @param int $transform
101
     * @return string
102 2
     */
103 2
    public static function transformData($data, $transform = Cache::TEXT)
104 2
    {
105 1
        switch ($transform) {
106
            case Cache::JSON:
107 1
                $data = json_encode($data, JSON_PRETTY_PRINT);
108 1
                break;
109
            case Cache::JSONGZ:
110 1
                $data = Cache::transformData($data, Cache::JSON);
111
                $data = Cache::transformData($data, Cache::GZIP);
112 2
                break;
113
            case Cache::GZIP:
114
                if(function_exists('gzcompress')) {
115
                    $data = gzcompress($data);
116
                }
117
                break;
118
        }
119
        return $data;
120
    }
121
122 2
    /**
123
     * Método que guarda en fichero los datos pasados
124 2
     * @param $path
125 2
     * @param $data
126 2
     * @param int $transform
127
     * @param boolean $absolutePath
128
     */
129
    public function storeData($path, $data, $transform = Cache::TEXT, $absolutePath = false)
130
    {
131
        $data = Cache::transformData($data, $transform);
132
        $this->saveTextToFile($data, $path, $absolutePath);
133
    }
134
135
    /**
136
     * Método que verifica si tiene que leer o no un fichero de cache
137
     * @param string $path
138
     * @param int $expires
139
     * @param callable $function
140
     * @param int $transform
141
     * @return string|null
142
     */
143
    public function readFromCache($path, $expires = 300, callable $function, $transform = Cache::TEXT)
144
    {
145
        $data = null;
146
        if (file_exists(CACHE_DIR . DIRECTORY_SEPARATOR . $path)) {
147
            if (null !== $function && $this->hasExpiredCache($path, $expires)) {
148
                $data = call_user_func($function);
149
                $this->storeData($path, $data, $transform);
150
            } else {
151
                $data = $this->getDataFromFile($path, $transform);
152
            }
153
        }
154
        return $data;
155
    }
156
157
    /**
158
     * Método estático que revisa si se necesita cachear la respuesta de un servicio o no
159
     * @return integer
160
     */
161
    public static function needCache()
162
    {
163
        $action = Security::getInstance()->getSessionKey("__CACHE__");
164
        $needCache = false;
165
        if (null !== $action && array_key_exists("cache", $action) && $action["cache"] > 0) {
166
            $needCache = $action["cache"];
167
        }
168
        return $needCache;
169
    }
170
171
    /**
172
     * Método que construye un hash para almacenar la cache
173
     * @return string
174
     */
175
    public function getRequestCacheHash()
176
    {
177
        $hash = "";
178
        $action = Security::getInstance()->getSessionKey("__CACHE__");
179
        if (null !== $action && $action["cache"] > 0) {
180
            $hash = $action["http"] . " " . $action["slug"];
181
        }
182
        return sha1($hash);
183
    }
184
}
185