Completed
Pull Request — master (#41)
by Nicolas
07:53
created

StreamedFile::asTransported()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 12

Duplication

Lines 11
Ratio 52.38 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 11
loc 21
ccs 0
cts 16
cp 0
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 12
nc 2
nop 0
crap 6
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))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
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