Skip to content

Instantly share code, notes, and snippets.

@carnage
Created February 9, 2016 13:45
Show Gist options
  • Save carnage/68d6263e1844da8dcf4a to your computer and use it in GitHub Desktop.
Save carnage/68d6263e1844da8dcf4a to your computer and use it in GitHub Desktop.
Create Temp files/dirs symfony filesystem
<?php
namespace Filesystem;
use Symfony\Component\Filesystem\Filesystem as BaseFileSystem;
use Symfony\Component\Filesystem\LockHandler;
/**
* Class Filesystem
*/
class Filesystem extends BaseFileSystem
{
/**
* @param $path
* @param string $prefix
* @return string
*/
public function createTmpDir($path, $prefix = '')
{
$lock = new LockHandler(hash('sha256', $path));
$lock->lock(true);
do {
$dirname = $path . DIRECTORY_SEPARATOR . uniqid($prefix);
} while ($this->exists($dirname));
$this->mkdir($dirname);
register_shutdown_function(
function () use ($dirname) {
$this->remove($dirname);
}
);
$lock->release();
return $dirname;
}
/**
* @param $path
* @param string $prefix
* @return string
*/
public function createTmpFile($path, $prefix = '')
{
$lock = new LockHandler(hash('sha256', $path));
$lock->lock(true);
do {
$filename = $path . DIRECTORY_SEPARATOR . uniqid($prefix);
} while ($this->exists($filename));
$this->touch($filename);
register_shutdown_function(
function () use ($filename) {
$this->remove($filename);
}
);
$lock->release();
return $filename;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment