Test Failed
Push — master ( c137c2...5643bc )
by Никита
18:22
created

FileStorage   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 255
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 3
dl 0
loc 255
ccs 137
cts 137
cp 1
rs 8.3999
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 25 6
A set_value() 0 22 3
B create_path() 0 26 6
B get_value_full_clear() 0 18 5
A get_filename() 0 3 1
A get_folder() 0 9 2
A get_mutex_key_name() 0 4 1
A create_lock() 0 8 1
A delete_value() 0 13 2
A sad_safe_reg() 0 13 3
A delete_all_files_in_folder() 0 9 4
C clear() 0 34 12

How to fix   Complexity   

Complex Class

Complex classes like FileStorage often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FileStorage, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
    namespace NokitaKaze\KeyValue;
4
5
    use NokitaKaze\Mutex\MutexInterface;
6
    use NokitaKaze\Mutex\FileMutex;
7
8
    /**
9
     * Class Key-value хранилище, использующее обыкновенные файлы
10
     */
11
    class FileStorage extends AbstractStorage {
12
        var $folder;
13
        protected $_multi_folder = false;
14
        const ERROR_CODE = 100;
15
16
        /**
17
         * @param KeyValueSettings|object $settings
18
         *
19
         * @throws KeyValueException
20
         */
21 180
        function __construct($settings) {
1 ignored issue
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
22 180
            if (!isset($settings->storage_type)) {
23 174
                $settings->storage_type = self::StorageTemporary;
24 58
            }
25 180
            switch ($settings->storage_type) {
26 180
                case self::StorageTemporary:
27 180
                    $this->folder = sys_get_temp_dir();
28 180
                    break;
29 6
                case self::StoragePersistent:
30 6
                    $this->folder = FileMutex::getDirectoryString();
31 6
                    break;
32 2
                default:
33 6
                    throw new KeyValueException('Constructor settings is malformed. Storage type can not be equal '.
34 6
                                                $settings->storage_type, self::ERROR_CODE + 1);
35 60
            }
36 180
            if (isset($settings->folder)) {
37 174
                $this->folder = $settings->folder;
38 58
            }
39 180
            if (isset($settings->multi_folder)) {
40 36
                $this->_multi_folder = (boolean) $settings->multi_folder;
41 12
            }
42
43 180
            $this->settings = $settings;
44 180
            $this->standard_prefix_strategy();
45 180
        }
46
47
        /**
48
         * @param string         $key   Название ключа
49
         * @param mixed          $value Новое значение
50
         * @param double|integer $ttl   Кол-во секунд, после которых значение будет считаться просроченным
51
         *
52
         * @throws KeyValueException
53
         */
54 66
        function set_value($key, $value, $ttl = 315576000) {
1 ignored issue
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
55 66
            $ts1 = microtime(true);
56 66
            $data = $this->form_datum_value($key, $value, $ttl);
57 66
            self::create_path($this->folder, $this->_multi_folder, $key);
58 60
            $this->get_lock($key);
59 60
            $temporary_filename = $this->get_filename($key).'.tmp';
60 60
            $result = @file_put_contents($temporary_filename, serialize($data), LOCK_EX);
61 60
            if ($result === false) {
62 6
                $this->release_lock();
63 6
                throw new KeyValueException('Can not save value', self::ERROR_CODE + 3);
64
            }
65 60
            chmod($temporary_filename, 6 << 6);
66 60
            if (!rename($temporary_filename, $this->get_filename($key))) {
67
                // @codeCoverageIgnoreStart
68
                @unlink($temporary_filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
69
                $this->release_lock();
70
                throw new KeyValueException('Can not rename db file', self::ERROR_CODE + 4);
71
                // @codeCoverageIgnoreEnd
72
            }
73 60
            $this->release_lock();
74 60
            self::add_profiling(microtime(true) - $ts1, static::class, 'set_value');
75 60
        }
76
77
        /**
78
         * Создаём папку
79
         *
80
         * @param string  $folder
81
         * @param boolean $multi_folder
82
         * @param string  $key
83
         *
84
         * @throws KeyValueException
85
         */
86 72
        protected static function create_path($folder, $multi_folder, $key) {
87 72
            if (!file_exists($folder)) {
88 12
                if (!file_exists(dirname($folder))) {
89 12
                    throw new KeyValueException(sprintf('Folder %s does not exist', dirname($folder)),
90 12
                        self::ERROR_CODE + 5);
91
                } else {
92 6
                    mkdir($folder);
93 6
                    chmod($folder, (7 << 6) | (7 << 3));
94
                }
95 2
            }
96
97 66
            if (!$multi_folder) {
98 42
                return;
99
            }
100 30
            $hash = hash('sha512', $key);
101 30
            $folder .= '/'.substr($hash, 0, 2);
102 30
            if (!file_exists($folder)) {
103 30
                mkdir($folder);
104 30
                chmod($folder, (7 << 6) | (7 << 3));
105 10
            }
106 30
            $folder .= '/'.substr($hash, 2, 2);
107 30
            if (!file_exists($folder)) {
108 30
                mkdir($folder);
109 30
                chmod($folder, (7 << 6) | (7 << 3));
110 10
            }
111 30
        }
112
113
        /**
114
         * @param string $key
115
         *
116
         * @return object|null
117
         */
118 72
        protected function get_value_full_clear($key) {
119 72
            $filename = $this->get_filename($key);
120 72
            if (!file_exists($filename)) {
121 72
                return null;
122
            }
123 66
            $this->get_lock($key);
124 66
            $buf = @file_get_contents($filename);
125 66
            $this->release_lock();
126 66
            if ($buf === false) {
127 6
                return null;
128
            }
129 66
            $data = @unserialize($buf);
130 66
            if (($data === false) and ($buf != serialize(false))) {
131 6
                return null;
132
            }
133
134 66
            return $data;
135
        }
136
137
        /**
138
         * @param string $key
139
         *
140
         * @return string
141
         */
142 168
        function get_filename($key) {
143 168
            return $this->get_folder($key).'/ascetkey_'.$this->_prefix.hash('sha512', $key).'.dat';
144
        }
145
146 72
        function get_folder($key) {
147 72
            $full_folder = $this->folder;
148 72
            if ($this->_multi_folder) {
149 24
                $hash = hash('sha512', $key);
150 24
                $full_folder .= sprintf('/%s/%s', substr($hash, 0, 2), substr($hash, 2, 2));
151 8
            }
152
153 72
            return $full_folder;
154
        }
155
156
        /**
157
         * Key for NokitaKaze\Mutex\MutexInterface
158
         *
159
         * @param string $key
160
         *
161
         * @return string
162
         */
163 168
        function get_mutex_key_name($key) {
164
            // @hint Мы используем sha256, а не sha512, потому что иначе у нас просто не хватит длины
165 168
            return 'ascetkey_'.hash('sha256', $this->get_filename($key));
166
        }
167
168
        /**
169
         * Создаём мьютекс, соответствующий ключу и кладём его в _locks
170
         *
171
         * @param string $key
172
         */
173 72
        protected function create_lock($key) {
174
            // @todo Любой мьютекс
175 72
            $this->_locks[$key] = new FileMutex([
176 72
                'name' => $this->get_mutex_key_name($key),
177 72
                'type' => MutexInterface::SERVER,
178 72
                'folder' => $this->get_folder($key),
179 24
            ]);
180 72
        }
181
182
        /**
183
         * @param string $key
184
         */
185 30
        function delete_value($key) {
186 30
            $ts1 = microtime(true);
187 30
            $filename = $this->get_filename($key);
188 30
            if (!file_exists($filename)) {
189 30
                self::add_profiling(microtime(true) - $ts1, static::class, 'delete_value');
190
191 30
                return;
192
            }
193 18
            $this->get_lock($key);
194 18
            @unlink($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
195 18
            $this->release_lock();
196 18
            self::add_profiling(microtime(true) - $ts1, static::class, 'delete_value');
197 18
        }
198
199
        /**
200
         * Санация части regexp для добавления напрямую в regexp
201
         *
202
         * @param string $text Часть, которую над санировать
203
         *
204
         * @return string
205
         * @codeCoverageIgnore
206
         */
207
        protected static function sad_safe_reg($text) {
208
            $ar = '.-\\/[]{}()*?+^$|';
209
            $s = '';
210
            for ($i = 0; $i < strlen($text); $i++) {
211
                if (strpos($ar, $text[$i]) !== false) {
212
                    $s .= '\\'.$text[$i];
213
                } else {
214
                    $s .= $text[$i];
215
                }
216
            }
217
218
            return $s;
219
        }
220
221 24
        protected function delete_all_files_in_folder($folder) {
222 24
            foreach (scandir($folder) as $d) {
223 24
                if (!in_array($d, ['.', '..']) and
224 24
                    preg_match('|^ascetkey_'.self::sad_safe_reg($this->_prefix).'[a-f0-9]{128,128}\\.dat$|', $d)
225 8
                ) {
226 24
                    unlink($folder.'/'.$d);
227 8
                }
228 8
            }
229 24
        }
230
231 30
        function clear() {
232 30
            if (!file_exists($this->folder) or !is_dir($this->folder)) {
233 6
                return;
234
            }
235 24
            if (!$this->_multi_folder) {
236 12
                $this->delete_all_files_in_folder($this->folder);
237 4
            } else {
238 12
                for ($i = 0; $i < 256; $i++) {
239
                    // @todo заменить на pack
240 12
                    if ($i < 16) {
241 12
                        $k1 = '0'.dechex($i);
242 4
                    } else {
243 12
                        $k1 = dechex($i);
244
                    }
245 12
                    if (!file_exists($this->folder.'/'.$k1) or !is_dir($this->folder.'/'.$k1)) {
246 6
                        continue;
247
                    }
248
249 12
                    for ($j = 0; $j < 256; $j++) {
250
                        // @todo заменить на pack
251 12
                        if ($j < 16) {
252 12
                            $k2 = '0'.dechex($j);
253 4
                        } else {
254 12
                            $k2 = dechex($j);
255
                        }
256
257 12
                        $full_folder = $this->folder.'/'.$k1.'/'.$k2;
258 12
                        if (file_exists($full_folder) and is_dir($full_folder)) {
259 12
                            $this->delete_all_files_in_folder($full_folder);
260 4
                        }
261 4
                    }
262 4
                }
263
            }
264 24
        }
265
    }
266
267
?>
1 ignored issue
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...