Completed
Push — master ( 02960d...339654 )
by
unknown
01:57
created

MediaStream::getZipStreamContents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\MediaLibrary;
4
5
use ZipStream\ZipStream;
6
use Illuminate\Support\Collection;
7
use Spatie\MediaLibrary\Models\Media;
8
use Illuminate\Contracts\Support\Responsable;
9
use Symfony\Component\HttpFoundation\StreamedResponse;
10
11
class MediaStream implements Responsable
12
{
13
    /** string */
14
    protected $zipName;
15
16
    /** Illuminate\Support\Collection */
17
    protected $mediaItems;
18
19
    public static function create(string $zipName)
20
    {
21
        return new static($zipName);
22
    }
23
24
    public function __construct(string $zipName)
25
    {
26
        $this->zipName = $zipName;
27
28
        $this->mediaItems = collect();
29
    }
30
31
    public function addMedia(...$mediaItems)
32
    {
33
        collect($mediaItems)
34
            ->flatMap(function ($item) {
35
                if ($item instanceof Media) {
36
                    return [$item];
37
                }
38
39
                if ($item instanceof Collection) {
40
                    return $item->reduce(function (array $carry, Media $media) {
41
                        $carry[] = $media;
42
43
                        return $carry;
44
                    }, []);
45
                }
46
47
                return $item;
48
            })
49
            ->each(function (Media $media) {
50
                $this->mediaItems->push($media);
51
            });
52
53
        return $this;
54
    }
55
56
    public function getMediaItems(): Collection
57
    {
58
        return $this->mediaItems;
59
    }
60
61
    public function toResponse($request)
62
    {
63
        return new StreamedResponse(function () {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp... $zip->finish(); }); (Symfony\Component\HttpFoundation\StreamedResponse) is incompatible with the return type declared by the interface Illuminate\Contracts\Sup...Responsable::toResponse of type Illuminate\Http\Response.

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...
64
            $zip = new ZipStream($this->zipName);
65
66
            $this->getZipStreamContents()->each(function (array $mediaInZip) use ($zip) {
67
                $stream = $mediaInZip['media']->stream();
68
69
                $zip->addFileFromStream($mediaInZip['fileNameInZip'], $stream);
70
71
                fclose($stream);
72
            });
73
74
            $zip->finish();
75
        });
76
    }
77
78
    protected function getZipStreamContents(): Collection
79
    {
80
        return $this->mediaItems->map(function (Media $media, $mediaItemIndex) {
81
            return [
82
                'fileNameInZip' => $this->getFileNameWithSuffix($this->mediaItems, $mediaItemIndex),
83
                'media' => $media,
84
            ];
85
        });
86
    }
87
88
    protected function getFileNameWithSuffix(Collection $mediaItems, int $currentIndex): string
89
    {
90
        $fileNameCount = 0;
91
92
        $fileName = $mediaItems[$currentIndex]->file_name;
93
94
        foreach($mediaItems as $index => $media) {
95
            if ($index >= $currentIndex) {
96
                break;
97
            }
98
99
            if ($media->file_name === $fileName) {
100
                $fileNameCount++;
101
            }
102
        }
103
104
        if ($fileNameCount === 0) {
105
            return $fileName;
106
        }
107
108
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);
109
        $fileNameWithoutExtension = pathinfo($fileName, PATHINFO_FILENAME);
110
111
        return "{$fileNameWithoutExtension} ({$fileNameCount}).{$extension}";
112
    }
113
}
114