3 namespace Services\Uploads
;
5 use Services\Uploads\IUploadManager
;
6 use Services\Uploads\IFileFactory
;
7 use Services\Uploads\IFile
;
10 class UploadManager
implements IUploadManager
{
12 private $_files= array();
13 private $_fileFactory;
14 private $_destination;
16 public function __construct(IFileFactory
$fileFactory) {
17 $this->_fileFactory
= $fileFactory;
20 foreach($_FILES as $file)
22 $this->_files
[] = $this->_fileFactory
->createInstance(
32 public function setDestination($path) {
33 if(!$this->destinationExists($path))
35 throw new Exception('Invalid path. Path does not exist.');
38 $this->_destination
= $path;
43 private function destinationExists($path) {
44 return file_exists($path);
47 private function saveFile(IFile
$file)
49 if($this->_destination
)
51 $randomName = $this->randomFilename();
52 $result = move_uploaded_file($file->getTempName(), $this->_destination
. '/' . $randomName . '.' . $file->getExtension());
57 throw new Exception("Could not save file.");
63 private function randomFilename()
65 return sha1(mt_rand(1, 9999) . $this->_destination
. uniqid() . time());
68 public function process()
72 foreach($this->_files
as $file)
74 $results[$file->getName()] = $this->saveFile($file);