1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Puzzle\AMQP\Messages\Bodies; |
4
|
|
|
|
5
|
|
|
use Puzzle\AMQP\Messages\Body; |
6
|
|
|
use Puzzle\AMQP\Messages\Chunks\Chunk; |
7
|
|
|
use Puzzle\AMQP\Messages\Chunks\ChunkedMessageMetadata; |
8
|
|
|
use Puzzle\ValueObjects\Uuid; |
9
|
|
|
use Puzzle\AMQP\Messages\ContentType; |
10
|
|
|
use Puzzle\AMQP\Messages\Chunks\ChunkSize; |
11
|
|
|
|
12
|
|
|
class StreamedFile implements Body |
13
|
|
|
{ |
14
|
|
|
private |
15
|
|
|
$filepath, |
16
|
|
|
$chunkSize, |
17
|
|
|
$metadata; |
18
|
|
|
|
19
|
|
|
public function __construct($filepath, ChunkSize $chunkSize) |
20
|
|
|
{ |
21
|
|
|
$this->ensureFilepathIsValid($filepath); |
22
|
|
|
|
23
|
|
|
$this->filepath = $filepath; |
24
|
|
|
$this->chunkSize = $chunkSize; |
25
|
|
|
|
26
|
|
|
$size = filesize($filepath); |
27
|
|
|
$nbChunks = (int) ceil($size / $chunkSize->toBytes()); |
28
|
|
|
|
29
|
|
|
$this->metadata = new ChunkedMessageMetadata(new Uuid(), $size, $nbChunks, sha1_file($filepath)); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function ensureFilepathIsValid($filepath) |
33
|
|
|
{ |
34
|
|
|
if(is_file($filepath) === false || is_readable($filepath) === false) |
35
|
|
|
{ |
36
|
|
|
throw new \InvalidArgumentException("Cannot read $filepath"); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function inOriginalFormat() |
41
|
|
|
{ |
42
|
|
|
return file_get_contents($this->filepath); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @return \Generator |
47
|
|
|
*/ |
48
|
|
|
public function asTransported() |
49
|
|
|
{ |
50
|
|
|
$offset = 0; |
51
|
|
|
$playhead = 0; |
52
|
|
|
|
53
|
|
|
$stream = fopen($this->filepath, 'r'); |
54
|
|
|
|
55
|
|
View Code Duplication |
while(! feof($stream)) |
|
|
|
|
56
|
|
|
{ |
57
|
|
|
$content = fread($stream, $this->chunkSize->toBytes()); |
58
|
|
|
$playhead++; |
59
|
|
|
|
60
|
|
|
$chunk = new Chunk($playhead, $offset, $content, $this->metadata); |
61
|
|
|
yield $chunk; |
62
|
|
|
|
63
|
|
|
$offset += $chunk->size(); |
64
|
|
|
unset($chunk, $content); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
fclose($stream); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function getContentType() |
71
|
|
|
{ |
72
|
|
|
return ContentType::BINARY; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function __toString() |
76
|
|
|
{ |
77
|
|
|
return sprintf( |
78
|
|
|
'<binary stream of %d bytes>', |
79
|
|
|
filesize($this->filepath) |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.