/** * Run the file rotation * * @return array Array of files which have been rotated * @throws FilenameFormatException * @throws RotateException */ public function run() { if (!$this->hasFilenameFormat()) { throw new FilenameFormatException('You must set a filename format to match files against'); } $rotated = []; $dir = new DirectoryIterator($this->getFilenameFormat()->getPath()); $dir->setFilenameFormat($this->getFilenameFormat()); foreach ($dir as $file) { if ($file->isFile() && $file->isMatch()) { // Skip if rotate size specified and initial matched file doesn't exceed this if ($this->hasSizeToRotate()) { if ($file->getSize() < $this->getSizeToRotate()) { continue; } } // Rotate files for ($x = $this->keepNumber; $x--; $x > 0) { $fileToRotate = $file->getPath() . '/' . $file->getRotatedFilename($x); if (!file_exists($fileToRotate)) { continue; } if ($x === $this->keepNumber) { if (!$this->isDryRun()) { if (!unlink($fileToRotate)) { throw new RotateException('Cannot delete file: ' . $file->getRotatedFilename($x)); } } $rotated[] = $fileToRotate; } else { if (!$this->isDryRun()) { if (!rename($fileToRotate, $file->getPath() . '/' . $file->getRotatedFilename($x + 1))) { throw new RotateException('Cannot rotate file: ' . $file->getRotatedFilename($x)); } } $rotated[] = $fileToRotate; } } if (!$this->isDryRun()) { if (!rename($file->getPath() . '/' . $file->getBasename(), $file->getPath() . '/' . $file->getRotatedFilename(1))) { throw new RotateException('Cannot rotate file: ' . $file->getBasename()); } } $rotated[] = $file->getPath() . '/' . $file->getBasename(); } } return $rotated; }