* @package Mammut\Storage */ class FileBlobStorage extends \Mammut\StrictObject implements iBlobStorage { private $dir; private $subdirs = true; public function __construct($dir, $useSubdirs = true) { $this->dir = $dir; $this->subdirs = $useSubdirs; } private function buildFileName($uuid) { $uuid = strtolower($uuid); if ($this->subdirs) { $parts = explode('-', $uuid); $fname = $this->dir.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.blob'; } else $fname = $this->dir.DIRECTORY_SEPARATOR.$uuid.'.blob'; return $fname; } public function store($blob) { do { $uuid = UUID::generate(); } while ($this->exists($uuid)); $path = $this->buildFileName($uuid); $dir = dirname($path); $file = basename($path); if (!file_exists($dir)) mkdir($dir, 0770, true); if (file_exists($path)) throw new IllegalStateException($uuid.' exists'); if (is_string($blob)) { file_put_contents($path, $blob); return $uuid; } elseif ($blob instanceof iOutput) { $fp = fopen($path, 'w', false); while (!$blob->isEOF()) fwrite($fp, $blob->read(65535)); fclose($fp); return $uuid; } throw new ImplementationException(); } public function append($uuid, $blob) { throw new ImplementationException(); } public function replace($uuid, $blob) { $path = $this->buildFileName($uuid); if (!file_exists($path)) throw new FileNotFoundException($uuid); if (is_string($blob)) { file_put_contents($path, $blob); return; } elseif ($blob instanceof iOutput) { $fp = fopen($path, 'w', false); while (!$blob->isEOF()) fwrite($fp, $blob->read(65535)); fclose($fp); return; } throw new ImplementationException(); } public function exists($uuid) { $path = $this->buildFileName($uuid); return file_exists($path); } public function get($uuid) { $path = $this->buildFileName($uuid); if (!file_exists($path)) throw new FileNotFoundException($uuid); return file_get_contents($path); } public function getPart($uuid, $start, $lenght) { throw new ImplementationException(); } public function size($uuid) { $path = $this->buildFileName($uuid); if (!file_exists($path)) throw new FileNotFoundException($uuid); return filesize($path); } public function delete($uuid) { $path = $this->buildFileName($uuid); if (!file_exists($path)) throw new FileNotFoundException($uuid); unlink($path); } public function purge() { throw new ImplementationException(); } }