PluginProbe ʕ •ᴥ•ʔ
Backup Migration / 2.1.7
Backup Migration v2.1.7
2.1.7 2.1.6 2.1.5.2 trunk 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.7 1.3.8 1.3.9 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.4.5 1.4.6 1.4.6.1 1.4.7 1.4.8 1.4.9 1.4.9.1 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.5.1
backup-backup / analyst / src / Storage / FileStorage.php
backup-backup / analyst / src / Storage Last commit date
DatabaseStorage.php 2 weeks ago FileStorage.php 2 weeks ago
FileStorage.php
100 lines
1 <?php
2
3 namespace Analyst\Storage;
4
5 use Analyst\Contracts\StorageContract;
6
7 if ( ! defined( 'ABSPATH' ) ) exit;
8
9 /**
10 * Class FileStorage
11 *
12 * Persists key-value data as individual dotname files inside wp-content.
13 * Each key maps to a file named ".analyst_{key}" in WP_CONTENT_DIR.
14 * Values are serialized and base64-encoded to safely store arbitrary data.
15 */
16 class FileStorage implements StorageContract
17 {
18 /**
19 * Base directory for storage files.
20 *
21 * @var string
22 */
23 protected $directory;
24
25 public function __construct()
26 {
27 $this->directory = rtrim(WP_CONTENT_DIR, '/\\');
28 }
29
30 /**
31 * @param string $key
32 * @param mixed $default
33 * @return mixed
34 */
35 public function get($key, $default = null)
36 {
37 $filePath = $this->resolveFilePath($key);
38
39 if (!file_exists($filePath) || !is_readable($filePath)) {
40 return $default;
41 }
42
43 $encoded = @file_get_contents($filePath);
44
45 if ($encoded === false || $encoded === '') {
46 return $default;
47 }
48
49 $raw = base64_decode($encoded, true);
50
51 if ($raw === false) {
52 return $default;
53 }
54
55 return @unserialize($raw);
56 }
57
58 /**
59 * @param string $key
60 * @param mixed $value
61 * @return bool
62 */
63 public function put($key, $value)
64 {
65 $filePath = $this->resolveFilePath($key);
66
67 $encoded = base64_encode(serialize($value));
68
69 return @file_put_contents($filePath, $encoded, LOCK_EX) !== false;
70 }
71
72 /**
73 * @param string $key
74 * @return bool
75 */
76 public function delete($key)
77 {
78 $filePath = $this->resolveFilePath($key);
79
80 if (file_exists($filePath)) {
81 return @unlink($filePath);
82 }
83
84 return true;
85 }
86
87 /**
88 * Build the absolute file path for a given key.
89 *
90 * @param string $key
91 * @return string
92 */
93 private function resolveFilePath($key)
94 {
95 $safeKey = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $key);
96
97 return $this->directory . '/.analyst_' . $safeKey;
98 }
99 }
100