File upload stuff.
[rock.divinelegy.git] / Services / Uploads / UploadManager.php
1 <?php
2
3 namespace Services\Uploads;
4
5 use Services\Uploads\IUploadManager;
6 use Services\Uploads\IFileFactory;
7 use Services\Uploads\IFile;
8 use Exception;
9
10 class UploadManager implements IUploadManager{
11
12 private $_files= array();
13 private $_fileFactory;
14 private $_destination;
15
16 public function __construct(IFileFactory $fileFactory) {
17 $this->_fileFactory = $fileFactory;
18
19 if($_FILES) {
20 foreach($_FILES as $file)
21 {
22 $this->_files[] = $this->_fileFactory->createInstance(
23 $file['name'],
24 $file['type'],
25 $file['tmp_name'],
26 $file['size']
27 );
28 }
29 }
30 }
31
32 public function setDestination($path) {
33 if(!$this->destinationExists($path))
34 {
35 throw new Exception('Invalid path. Path does not exist.');
36 }
37
38 $this->_destination = $path;
39
40 return $this;
41 }
42
43 private function destinationExists($path) {
44 return file_exists($path);
45 }
46
47 private function saveFile(IFile $file)
48 {
49 if($this->_destination)
50 {
51 $randomName = $this->randomFilename();
52 $result = move_uploaded_file($file->getTempName(), $this->_destination . '/' . $randomName . '.' . $file->getExtension());
53 }
54
55 if(!$result)
56 {
57 throw new Exception("Could not save file.");
58 }
59
60 return $randomName;
61 }
62
63 private function randomFilename()
64 {
65 return sha1(mt_rand(1, 9999) . $this->_destination . uniqid() . time());
66 }
67
68 public function process()
69 {
70 $results = array();
71
72 foreach($this->_files as $file)
73 {
74 $results[$file->getName()] = $this->saveFile($file);
75 }
76
77 return $results;
78 }
79 }