_file) { $this->setFile(realpath(__DIR__ . '/../../tmp/cache') . '/image-size-registry.txt'); } return $this->_file; } public function setFile($file) { if (!$file || !($dir = dirname($file)) || !file_exists($dir)) { throw new Exception('Invalid file path'); } $this->_file = $file; return $this; } public function getSizes() { if (null === $this->_sizes) { $this->_sizes = $this->readSizes(); } return $this->_sizes; } public function isRegistered($width, $height) { return !empty($this->getSizes()) && false !== strpos($this->getSizes(), $this->createSize($width, $height)); } private function createSize($width, $height) { return $width . 'x' . $height . PHP_EOL; } public function register($width, $height) { $file = $this->getFile(); if (false === ($handle = fopen($file, 'a+'))) { throw new Exception('Failed to open file: ' . $file); } if (false === flock($handle, LOCK_EX)) { throw new Exception('Failed to lock file: ' . $file); } // force file re-read after writer lock to ensure we have fresh data which possibly updated by parallel process $this->_sizes = null; if (!$this->isRegistered($width, $height)) { $size = $this->createSize($width, $height); fwrite($handle, $size); $this->_sizes .= $size; } flock($handle, LOCK_UN); fclose($handle); return $this; } private function readSizes() { $file = $this->getFile(); if (!file_exists($file)) { return ''; } if (false === ($content = file_get_contents($file))) { throw new Exception('Failed to read file ' . $file); } return $content; } }