class-file-progress-storage.php
3 months ago
interface-progress-storage.php
3 months ago
logger-only.php
3 months ago
migration.php
3 months ago
staging.php
3 months ago
zip.php
3 months ago
class-file-progress-storage.php
98 lines
| 1 | <?php |
| 2 | |
| 3 | namespace BMI\Plugin\Progress; |
| 4 | |
| 5 | require_once BMI_INCLUDES . '/progress/interface-progress-storage.php'; |
| 6 | |
| 7 | /** |
| 8 | * Class FileProgressStorage |
| 9 | * |
| 10 | * File-based implementation of ProgressStorageInterface. |
| 11 | * Stores progress as JSON in a temporary file. |
| 12 | */ |
| 13 | class FileProgressStorage implements ProgressStorageInterface |
| 14 | { |
| 15 | /** |
| 16 | * @var string The file path for storing progress. |
| 17 | */ |
| 18 | private $filePath; |
| 19 | |
| 20 | /** |
| 21 | * Constructor. |
| 22 | * |
| 23 | * @param string|null $storagePath Optional custom storage path. Defaults to BMI_TMP directory. |
| 24 | * @param string $fileName The file name for the progress file. |
| 25 | */ |
| 26 | public function __construct($storagePath = null, $fileName = 'search-replace-report.json') |
| 27 | { |
| 28 | $basePath = $storagePath !== null ? $storagePath : (defined('BMI_TMP') ? BMI_TMP : sys_get_temp_dir()); |
| 29 | $this->filePath = rtrim($basePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $fileName; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * {@inheritdoc} |
| 34 | */ |
| 35 | public function load() |
| 36 | { |
| 37 | if (!$this->exists()) { |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | $content = file_get_contents($this->filePath); |
| 42 | if ($content === false) { |
| 43 | return null; |
| 44 | } |
| 45 | |
| 46 | $data = json_decode($content, true); |
| 47 | if (json_last_error() !== JSON_ERROR_NONE) { |
| 48 | return null; |
| 49 | } |
| 50 | |
| 51 | return $data; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * {@inheritdoc} |
| 56 | */ |
| 57 | public function save($report) |
| 58 | { |
| 59 | $json = json_encode($report, JSON_PRETTY_PRINT); |
| 60 | if ($json === false) { |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | $result = file_put_contents($this->filePath, $json, LOCK_EX); |
| 65 | return $result !== false; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * {@inheritdoc} |
| 70 | */ |
| 71 | public function clear() |
| 72 | { |
| 73 | if (!$this->exists()) { |
| 74 | return true; |
| 75 | } |
| 76 | |
| 77 | return unlink($this->filePath); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * {@inheritdoc} |
| 82 | */ |
| 83 | public function exists() |
| 84 | { |
| 85 | return file_exists($this->filePath) && is_readable($this->filePath); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Gets the storage file path. |
| 90 | * |
| 91 | * @return string The file path. |
| 92 | */ |
| 93 | public function getFilePath() |
| 94 | { |
| 95 | return $this->filePath; |
| 96 | } |
| 97 | } |
| 98 |