Skip to content

Instantly share code, notes, and snippets.

@achepukov
Created July 2, 2018 06:57
Show Gist options
  • Save achepukov/711e52292be1c694e90da12a51f79818 to your computer and use it in GitHub Desktop.
Save achepukov/711e52292be1c694e90da12a51f79818 to your computer and use it in GitHub Desktop.
<?php
/**
* UniqueFileName
* Check whether file exists in path, and build unique name for them
*/
class UniqueFileName
{
/**
* @var string path to directory where file suppose to be located
*/
protected $path;
/**
* @param string $path path to directory with trailing slash
*/
public function __construct($path) {
$lastChar = substr($path, -1);
if ($lastChar !== DIRECTORY_SEPARATOR) {
throw new Exception("Path should contain trailing slash!");
}
$this->path = $path;
}
/**
* Build new name for file i.e. AAA.png -> AAA_1.png
* @param string $fileName file name with extension
* @return string new file name
*/
public function buildName($fileName) {
if (!$this->fileExists($fileName)) {
return $fileName;
}
$fileNameArray = explode(".", $fileName);
$extension = array_pop($fileNameArray);
$counter = 0;
$baseName = implode(".", $fileNameArray);
do {
$counter++;
$newName = $baseName . "_{$counter}." . $extension;
} while ($this->fileExists($newName));
return $newName;
}
/**
*
* @param string $fileName whether file exist
* @return bool
*/
protected function fileExists($fileName) {
return file_exists($this->path . $fileName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment