1
|
|
|
<?php |
2
|
|
|
namespace Staticus\Diactoros; |
3
|
|
|
|
4
|
|
|
use Psr\Http\Message\StreamInterface; |
5
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
6
|
|
|
use Staticus\Resources\Exceptions\SaveResourceErrorException; |
7
|
|
|
use Zend\Diactoros\Stream; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Special object for files, downloaded with curl, not from HTTP POST |
11
|
|
|
*/ |
12
|
|
|
class DownloadedFile implements UploadedFileInterface |
13
|
|
|
{ |
14
|
|
|
protected $file; |
15
|
|
|
protected $size; |
16
|
|
|
protected $moved = false; |
17
|
|
|
protected $stream; |
18
|
|
|
private $error; |
19
|
|
|
private $clientFilename; |
20
|
|
|
private $clientMediaType; |
21
|
|
|
|
22
|
|
|
public function __construct($file, $size, $error, $clientFilename = null, $clientMediaType = null) |
23
|
|
|
{ |
24
|
|
|
$this->file = $file; |
25
|
|
|
$this->size = $size; |
26
|
|
|
$this->error = $error; |
27
|
|
|
$this->clientFilename = $clientFilename; |
28
|
|
|
$this->clientMediaType = $clientMediaType; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function moveTo($targetPath) |
32
|
|
|
{ |
33
|
|
|
if (! is_string($targetPath)) { |
34
|
|
|
throw new SaveResourceErrorException( |
35
|
|
|
'Invalid path provided for move operation; must be a string' |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if (empty($targetPath)) { |
40
|
|
|
throw new SaveResourceErrorException( |
41
|
|
|
'Invalid path provided for move operation; must be a non-empty string' |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if ($this->moved) { |
46
|
|
|
throw new SaveResourceErrorException('Cannot move file; already moved!'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (false === rename($this->file, $targetPath)) { |
50
|
|
|
throw new SaveResourceErrorException('Error occurred while moving downloaded file'); |
51
|
|
|
} |
52
|
|
|
$this->moved = true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function getStream() |
56
|
|
|
{ |
57
|
|
|
if ($this->error !== UPLOAD_ERR_OK) { |
58
|
|
|
throw new SaveResourceErrorException('Cannot retrieve stream due to upload error'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if ($this->moved) { |
62
|
|
|
throw new SaveResourceErrorException('Cannot retrieve stream after it has already been moved'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if ($this->stream instanceof StreamInterface) { |
66
|
|
|
return $this->stream; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$this->stream = new Stream($this->file); |
70
|
|
|
return $this->stream; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function getSize() |
74
|
|
|
{ |
75
|
|
|
return $this->size; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function getError() |
79
|
|
|
{ |
80
|
|
|
return $this->error; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function getClientFilename() |
84
|
|
|
{ |
85
|
|
|
return $this->clientFilename; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
public function getClientMediaType() |
89
|
|
|
{ |
90
|
|
|
return $this->clientMediaType; |
91
|
|
|
} |
92
|
|
|
} |