filename = $filename; $this->directory = ltrim(dirname($filename), '.'); $name = basename($this->filename); // Note: Unlike normal extensions, we want to split at the first period, not the last. if (($pos = strpos($name, '.')) !== false) { $this->extension = substr($name, $pos); $name = substr($name, 0, $pos); } else { $this->extension = null; } // Extract version prefix if already applied to this file $this->padding = 0; $pattern = '/^(?[^\/]+?)' . preg_quote($this->getPrefix()) . '(?[0-9]+)$/'; if (preg_match($pattern, $name, $matches)) { $this->first = (int)$matches['version']; $this->name = $matches['name']; // Check if number is padded if (strpos($matches['version'], '0') === 0) { $this->padding = strlen($matches['version']); } } else { $this->first = 1; $this->name = $name; } $this->rewind(); } /** * Get numeric prefix * * @return string */ protected function getPrefix() { return Config::inst()->get(__CLASS__, 'version_prefix'); } public function current() { $version = $this->version; // Initially suggest original name if ($version === $this->first) { return $this->filename; } // If there are more than $this->max files we need a new scheme if ($version >= $this->max + $this->first - 1) { $version = substr(md5(time()), 0, 10); } elseif ($this->padding) { // Else, pad $version = str_pad($version, $this->padding, '0', STR_PAD_LEFT); } // Build next name $filename = $this->name . $this->getPrefix() . $version . $this->extension; if ($this->directory) { $filename = $this->directory . DIRECTORY_SEPARATOR . $filename; } return $filename; } public function key() { return $this->version - $this->first; } public function next() { $this->version++; } public function rewind() { $this->version = $this->first; } public function valid() { return $this->version < $this->max + $this->first; } public function getMaxTries() { return $this->max; } }