Test Failed
Push — master ( 728bda...d24de4 )
by Fran
03:38
created

Cache::checkAdminSite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\exception\ConfigException;
6
use PSFS\base\types\helpers\RequestHelper;
7
use PSFS\base\types\SingletonTrait;
8
9
/**
10
 * Class Cache
11
 * @package PSFS\base
12
 * Gestión de los ficheros de cache
13
 */
14
class Cache
15
{
16
17
    const JSON = 1;
18
    const TEXT = 2;
19
    const GZIP = 3;
20
    const JSONGZ = 4;
21
22
    use SingletonTrait;
23
24
    /**
25
     * Método que guarda un text en un fichero
26
     * @param string $data
27
     * @param string $path
28
     * @param boolean $absolute
29
     * @throws ConfigException
30 6
     */
31
    private function saveTextToFile($data, $path, $absolute = false)
32 6
    {
33 6
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
34 6
        $filename = basename($absolutePath);
35 6
        Config::createDir(str_replace($filename, "", $absolutePath));
36
        if (false === file_put_contents($absolutePath, $data)) {
37
            throw new ConfigException(_('No se tienen los permisos suficientes para escribir en el fichero ')
38
                . $absolutePath);
39 6
        }
40
    }
41
42
    /**
43
     * Método que extrae el texto de un fichero
44
     * @param string $path
45
     * @param int $transform
46
     * @param boolean $absolute
47
     * @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...
48 6
     */
49
    public function getDataFromFile($path, $transform = Cache::TEXT, $absolute = false)
50 6
    {
51 6
        $data = null;
52 6
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
53 5
        if (file_exists($absolutePath)) {
54 5
            $data = file_get_contents($absolutePath);
55 6
        }
56
        return Cache::extractDataWithFormat($data, $transform);
57
    }
58
59
    /**
60
     * Método que verifica si un fichero tiene la cache expirada
61
     * @param string $path
62
     * @param int $expires
63
     * @param boolean $absolute
64
     * @return bool
65 1
     */
66
    private function hasExpiredCache($path, $expires = 300, $absolute = false)
67 1
    {
68 1
        $absolutePath = ($absolute) ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path;
69 1
        $lasModificationDate = filemtime($absolutePath);
70
        return ($lasModificationDate + $expires <= time());
71
    }
72
73
    /**
74
     * Método que transforma los datos de salida
75
     * @param string $data
76
     * @param int $transform
77
     * @return array|string|null
78 6
     */
79
    public static function extractDataWithFormat($data, $transform = Cache::TEXT)
80
    {
81 6
        switch ($transform) {
82 6
            case Cache::JSON:
83 6
                $data = json_decode($data, true);
84 1
                break;
85 1
            case Cache::JSONGZ:
86 1
                $data = Cache::extractDataWithFormat($data, Cache::GZIP);
87 1
                $data = Cache::extractDataWithFormat($data, Cache::JSON);
88 1
                break;
89
            case Cache::GZIP:
90 1
                // TODO implementar
91 1
                if(function_exists('gzuncompress')) {
92 1
                    $data = gzuncompress($data ?: '');
93 1
                }
94
                break;
95 6
        }
96
        return $data;
97
    }
98
99
    /**
100
     * Método que transforma los datos de entrada del fichero
101
     * @param string $data
102
     * @param int $transform
103
     * @return string
104 6
     */
105
    public static function transformData($data, $transform = Cache::TEXT)
106
    {
107 6
        switch ($transform) {
108 6
            case Cache::JSON:
109 6
                $data = json_encode($data, JSON_PRETTY_PRINT);
110 2
                break;
111 1
            case Cache::JSONGZ:
112 1
                $data = Cache::transformData($data, Cache::JSON);
113 1
                $data = Cache::transformData($data, Cache::GZIP);
114 2
                break;
115 1
            case Cache::GZIP:
116 1
                if(function_exists('gzcompress')) {
117 1
                    $data = gzcompress($data ?: '');
118 1
                }
119
                break;
120 6
        }
121
        return $data;
122
    }
123
124
    /**
125
     * Método que guarda en fichero los datos pasados
126
     * @param $path
127
     * @param $data
128
     * @param int $transform
129
     * @param boolean $absolutePath
130 6
     */
131
    public function storeData($path, $data, $transform = Cache::TEXT, $absolutePath = false)
132 6
    {
133 6
        $data = Cache::transformData($data, $transform);
134 6
        $this->saveTextToFile($data, $path, $absolutePath);
135
    }
136
137
    /**
138
     * Método que verifica si tiene que leer o no un fichero de cache
139
     * @param string $path
140
     * @param int $expires
141
     * @param callable $function
142
     * @param int $transform
143
     * @return mixed
144 1
     */
145
    public function readFromCache($path, $expires = 300, callable $function, $transform = Cache::TEXT)
146 1
    {
147 1
        $data = null;
148 1
        if (file_exists(CACHE_DIR . DIRECTORY_SEPARATOR . $path)) {
149 1
            if (null !== $function && $this->hasExpiredCache($path, $expires)) {
150 1
                $data = call_user_func($function);
151 1
                $this->storeData($path, $data, $transform);
152 1
            } else {
153
                $data = $this->getDataFromFile($path, $transform);
154 1
            }
155 1
        }
156
        return $data;
157
    }
158
159
    /**
160
     * @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...
161
     */
162 1
    private function checkAdminSite() {
163
        $isAdminRequest = false;
164 1
        $lastRequest = Security::getInstance()->getSessionKey("lastRequest");
165 1
        if(null !== $lastRequest) {
166 1
            $url = str_replace(Request::getInstance()->getRootUrl(true), '', $lastRequest['url']);
167 1
            $isAdminRequest = preg_match('/^\/admin\//i', $url);
168 1
        }
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
        }
185
        return $needCache;
186
    }
187
188
    /**
189
     * Método que construye un hash para almacenar la cache
190
     * @return string
191
     */
192
    public function getRequestCacheHash()
193
    {
194
        $hash = "";
195
        $action = Security::getInstance()->getSessionKey("__CACHE__");
196
        if (null !== $action && $action["cache"] > 0) {
197
            $hash = $action["http"] . " " . $action["slug"];
198
        }
199
        return sha1($hash);
200
    }
201
}
202