Passed
Push — master ( ddf6f5...2e933f )
by Nicolas
03:42 queued 28s
created

StreamedFile::asTransportedInChunks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 12

Duplication

Lines 11
Ratio 52.38 %

Code Coverage

Tests 14
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 11
loc 21
ccs 14
cts 14
cp 1
rs 9.3142
cc 2
eloc 12
nc 2
nop 0
crap 2
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 5
    public function __construct($filepath, ChunkSize $chunkSize = null)
20
    {
21 5
        $this->ensureFilepathIsValid($filepath);
22
23 4
        $this->filepath = $filepath;
24 4
        $this->chunkSize = $chunkSize;
25
26 4
        $this->metadata = null;
27
28 4
        if($chunkSize instanceof ChunkSize)
29 4
        {
30 1
            $size = filesize($filepath);
31 1
            $nbChunks = (int) ceil($size / $chunkSize->toBytes());
32
33 1
            $this->metadata = new ChunkedMessageMetadata(new Uuid(), $size, $nbChunks, sha1_file($filepath));
34 1
        }
35 4
    }
36
37 5
    private function ensureFilepathIsValid($filepath)
38
    {
39 5
        if(is_file($filepath) === false || is_readable($filepath) === false)
40 5
        {
41 1
            throw new \InvalidArgumentException("Cannot read $filepath");
42
        }
43 4
    }
44
45 1
    public function inOriginalFormat()
46
    {
47 1
        return file_get_contents($this->filepath);
48
    }
49
50 2
    public function asTransported()
51
    {
52 2
        if($this->isChunked() === false)
53 2
        {
54 1
            return $this->inOriginalFormat();
55
        }
56
57 1
        return $this->asTransportedInChunks();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->asTransportedInChunks(); (Generator) is incompatible with the return type declared by the interface Puzzle\AMQP\Messages\Body::asTransported of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
58
    }
59
60
    /**
61
     * @return \Generator
62
     */
63 1
    private function asTransportedInChunks()
64
    {
65 1
        $offset = 0;
66 1
        $playhead = 0;
67
68 1
        $stream = fopen($this->filepath, 'r');
69
70 1 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...
71
        {
72 1
            $content = fread($stream, $this->chunkSize->toBytes());
73 1
            $playhead++;
74
75 1
            $chunk = new Chunk($playhead, $offset, $content, $this->metadata);
0 ignored issues
show
Bug introduced by
It seems like $this->metadata can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
76 1
            yield $chunk;
77
78 1
            $offset += $chunk->size();
79 1
            unset($chunk, $content);
80 1
        }
81
82 1
        fclose($stream);
83 1
    }
84
85 3
    public function getContentType()
86
    {
87 3
        return ContentType::BINARY;
88
    }
89
90 1
    public function __toString()
91
    {
92 1
        return sprintf(
93 1
            '<binary stream of %d bytes>',
94 1
            filesize($this->filepath)
95 1
        );
96
    }
97
98 4
    public function isChunked()
99
    {
100 4
        return $this->chunkSize instanceof ChunkSize;
101
    }
102
}
103