Completed
Push — master ( c350e4...2fe906 )
by Fran
08:21
created

Cache::storeData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 3
b 0
f 0
nc 1
nop 4
dl 0
loc 5
rs 9.4285
ccs 4
cts 4
cp 1
crap 1
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 5
    private function saveTextToFile($data, $path, $absolute = false)
31
    {
32 5
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
33 5
        $filename = basename($absolutePath);
34 5
        Config::createDir(str_replace($filename, "", $absolutePath));
35 5
        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 5
    }
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 5
    public function getDataFromFile($path, $transform = Cache::TEXT, $absolute = false)
48
    {
49 5
        $data = null;
50 5
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
51 5
        if (file_exists($absolutePath)) {
52 4
            $data = file_get_contents($absolutePath);
53 4
        }
54 5
        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 1
    private function hasExpiredCache($path, $expires = 300, $absolute = false)
65
    {
66 1
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
67 1
        $lasModificationDate = filemtime($absolutePath);
68 1
        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 5
    public static function extractDataWithFormat($data, $transform = Cache::TEXT)
78
    {
79
        switch ($transform) {
80 5
            case Cache::JSON:
81 5
                $data = json_decode($data, true);
82 5
                break;
83 1
            case Cache::JSONGZ:
84 1
                $data = Cache::extractDataWithFormat($data, Cache::GZIP);
85 1
                $data = Cache::extractDataWithFormat($data, Cache::JSON);
86 1
                break;
87 1
            case Cache::GZIP:
88
                // TODO implementar
89 1
                if(function_exists('gzuncompress')) {
90 1
                    $data = gzuncompress($data);
91 1
                }
92 1
                break;
93
        }
94 5
        return $data;
95
    }
96
97
    /**
98
     * Método que transforma los datos de entrada del fichero
99
     * @param string $data
100
     * @param int $transform
101
     * @return string
102
     */
103 5
    public static function transformData($data, $transform = Cache::TEXT)
104
    {
105
        switch ($transform) {
106 5
            case Cache::JSON:
107 5
                $data = json_encode($data, JSON_PRETTY_PRINT);
108 5
                break;
109 2
            case Cache::JSONGZ:
110 1
                $data = Cache::transformData($data, Cache::JSON);
111 1
                $data = Cache::transformData($data, Cache::GZIP);
112 1
                break;
113 2
            case Cache::GZIP:
114 1
                if(function_exists('gzcompress')) {
115 1
                    $data = gzcompress($data);
116 1
                }
117 1
                break;
118
        }
119 5
        return $data;
120
    }
121
122
    /**
123
     * Método que guarda en fichero los datos pasados
124
     * @param $path
125
     * @param $data
126
     * @param int $transform
127
     * @param boolean $absolutePath
128
     */
129 5
    public function storeData($path, $data, $transform = Cache::TEXT, $absolutePath = false)
130
    {
131 5
        $data = Cache::transformData($data, $transform);
132 5
        $this->saveTextToFile($data, $path, $absolutePath);
133 5
    }
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 1
    public function readFromCache($path, $expires = 300, callable $function, $transform = Cache::TEXT)
144
    {
145 1
        $data = null;
146 1
        if (file_exists(CACHE_DIR . DIRECTORY_SEPARATOR . $path)) {
147 1
            if (null !== $function && $this->hasExpiredCache($path, $expires)) {
148 1
                $data = call_user_func($function);
149 1
                $this->storeData($path, $data, $transform);
150 1
            } else {
151 1
                $data = $this->getDataFromFile($path, $transform);
152
            }
153 1
        }
154 1
        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|boolean
160
     */
161 1
    public static function needCache()
162
    {
163 1
        $action = Security::getInstance()->getSessionKey("__CACHE__");
164 1
        $needCache = false;
165 1
        if (null !== $action && array_key_exists("cache", $action) && $action["cache"] > 0) {
166 1
            $needCache = $action["cache"];
167 1
        }
168 1
        return $needCache;
169
    }
170
171
    /**
172
     * Método que construye un hash para almacenar la cache
173
     * @return string
174
     */
175 1
    public function getRequestCacheHash()
176
    {
177 1
        $hash = "";
178 1
        $action = Security::getInstance()->getSessionKey("__CACHE__");
179 1
        if (null !== $action && $action["cache"] > 0) {
180 1
            $hash = $action["http"] . " " . $action["slug"];
181 1
        }
182 1
        return sha1($hash);
183
    }
184
}
185