path = $path; $this->history = $history; } /** * Save an encoding. * * @param Encoding $encoding * @throws \RuntimeException */ public function save(Encoding $encoding) : void { if (!is_file($this->path) and !is_writable(dirname($this->path))) { throw new RuntimeException('Folder does not exist or is not writable'); } if (is_file($this->path) and !is_writable($this->path)) { throw new RuntimeException("File {$this->path} is not writable."); } if ($encoding->bytes() === 0) { throw new RuntimeException('Encoding does not contain any data.'); } if ($this->history and is_file($this->path)) { $timestamp = (string) time(); $filename = "{$this->path}-$timestamp." . self::HISTORY_EXT; $num = 0; while (is_file($filename)) { $filename = "{$this->path}-$timestamp-" . ++$num . '.' . self::HISTORY_EXT; } if (!rename($this->path, $filename)) { throw new RuntimeException('Could not create history file.'); } } $success = file_put_contents($this->path, $encoding->data(), LOCK_EX); if (!$success) { throw new RuntimeException('Could not write to the filesystem.'); } } /** * Load a persisted encoding. * * @throws \RuntimeException * @return Encoding */ public function load() : Encoding { if (!is_file($this->path)) { throw new RuntimeException("File {$this->path} does not exist."); } if (!is_readable($this->path)) { throw new RuntimeException("File {$this->path} is not readable."); } $data = file_get_contents($this->path); if ($data === false) { throw new RuntimeException('Could not load data from filesystem.'); } $encoding = new Encoding($data); if ($encoding->bytes() === 0) { throw new RuntimeException('File does not contain any data.'); } return $encoding; } /** * Return the string representation of the object. * * @internal * * @return string */ public function __toString() : string { return "Filesystem (path: {$this->path}, history: " . Params::toString($this->history) . ')'; } }