Pop\File\File::checkDupe PHP Method

checkDupe() public static method

Static method to check for a duplicate file, returning the next incremented filename, i.e. filename_1.txt
public static checkDupe ( string $file, string $dir = null ) : string
$file string
$dir string
return string
    public static function checkDupe($file, $dir = null)
    {
        if (null === $dir) {
            $dir = getcwd();
        }
        $newFilename = $file;
        $parts = pathinfo($file);
        $origFilename = $parts['filename'];
        $ext = isset($parts['extension']) && $parts['extension'] != '' ? '.' . $parts['extension'] : null;
        $i = 1;
        while (file_exists($dir . DIRECTORY_SEPARATOR . $newFilename)) {
            $newFilename = $origFilename . '_' . $i . $ext;
            $i++;
        }
        return $newFilename;
    }

Usage Example

Example #1
0
 public function testCheckDupe()
 {
     $f = File::checkDupe('access.txt', __DIR__ . '/../tmp');
     $this->assertEquals('access_1.txt', $f);
     $f = File::checkDupe('access.txt');
     $this->assertEquals('access.txt', $f);
 }
All Usage Examples Of Pop\File\File::checkDupe