3 namespace Services\Uploads
;
5 use Services\Uploads\IUploadManager
;
6 use Services\Uploads\IFileFactory
;
7 use Services\Uploads\IFile
;
8 //This was a bit silly, I have a File object to use with the service but there is also a File entity.
9 //It's confusing but if you pay attention it should be OK.
10 use Domain\Entities\IFileStepByStepBuilder
;
13 class UploadManager
implements IUploadManager
{
15 private $_files= array();
16 private $_fileFactory;
18 private $_destination;
19 private $_fileBuilder;
21 public function __construct(IFileFactory
$fileFactory, IFileStepByStepBuilder
$builder) {
22 $this->_fileFactory
= $fileFactory;
23 $this->_fileBuilder
= $builder;
26 foreach($_FILES as $file)
28 $this->_files
[] = $this->_fileFactory
->createInstance(
38 public function setFilesDirectory($path) {
39 if(!$this->destinationExists($path))
41 throw new Exception('Invalid path. Path does not exist.');
44 $this->_basePath
= $path;
49 public function setDestination($path) {
50 if(!$this->destinationExists($this->_basePath
. '/' . $path))
52 throw new Exception('Invalid path. Path does not exist.');
55 $this->_destination
= $path;
60 private function destinationExists($path) {
61 return file_exists($path);
64 private function saveFile(IFile
$file)
66 if($this->_destination
)
68 $randomName = $this->randomFilename();
69 $result = move_uploaded_file($file->getTempName(), $this->_basePath
. '/' . $this->_destination
. '/' . $randomName . '.' . $file->getExtension());
74 throw new Exception("Could not save file.");
80 private function randomFilename()
82 return sha1(mt_rand(1, 9999) . $this->_destination
. uniqid() . time());
85 public function process()
89 foreach($this->_files
as $file)
91 $hash = $this->saveFile($file);
93 /* @var $file \Services\Uploads\IFile */
94 $results[] = $this->_fileBuilder
->With_Hash($hash)
95 ->With_Path(rtrim($this->_destination
, '/'))
96 ->With_Filename($file->getName())
97 ->With_Mimetype($file->getType())
98 ->With_Size($file->getSize())
99 ->With_UploadDate(time())