81c12c7b43c654252f377d22328410a5d162f3a6
[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 //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;
11 use Exception;
12
13 class UploadManager implements IUploadManager{
14
15 private $_files= array();
16 private $_fileFactory;
17 private $_basePath;
18 private $_destination;
19 private $_fileBuilder;
20
21 public function __construct(IFileFactory $fileFactory, IFileStepByStepBuilder $builder) {
22 $this->_fileFactory = $fileFactory;
23 $this->_fileBuilder = $builder;
24
25 if($_FILES) {
26 foreach($_FILES as $file)
27 {
28 $this->_files[] = $this->_fileFactory->createInstance(
29 $file['name'],
30 $file['type'],
31 $file['tmp_name'],
32 $file['size']
33 );
34 }
35 }
36 }
37
38 public function setFilesDirectory($path) {
39 if(!$this->destinationExists($path))
40 {
41 throw new Exception('Invalid path. Path does not exist.');
42 }
43
44 $this->_basePath = $path;
45
46 return $this;
47 }
48
49 public function setDestination($path) {
50 if(!$this->destinationExists($this->_basePath . '/' . $path))
51 {
52 throw new Exception('Invalid path. Path does not exist.');
53 }
54
55 $this->_destination = $path;
56
57 return $this;
58 }
59
60 private function destinationExists($path) {
61 return file_exists($path);
62 }
63
64 private function saveFile(IFile $file)
65 {
66 if($this->_destination)
67 {
68 $randomName = $this->randomFilename();
69 $result = move_uploaded_file($file->getTempName(), $this->_basePath . '/' . $this->_destination . '/' . $randomName . '.' . $file->getExtension());
70 }
71
72 if(!$result)
73 {
74 throw new Exception("Could not save file.");
75 }
76
77 return $randomName;
78 }
79
80 private function randomFilename()
81 {
82 return sha1(mt_rand(1, 9999) . $this->_destination . uniqid() . time());
83 }
84
85 public function process()
86 {
87 $results = array();
88
89 foreach($this->_files as $file)
90 {
91 $hash = $this->saveFile($file);
92
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())
100 ->build();
101 }
102
103 return $results;
104 }
105 }