Completed
Pull Request — master (#903)
by Shiro
02:09
created

Media::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Spatie\MediaLibrary;
4
5
use DateTimeInterface;
6
use Illuminate\Support\Collection;
7
use Spatie\MediaLibrary\Helpers\File;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Contracts\Support\Responsable;
10
use Spatie\MediaLibrary\Conversion\Conversion;
11
use Spatie\MediaLibrary\Conversion\ConversionCollection;
12
use Spatie\MediaLibrary\UrlGenerator\UrlGeneratorFactory;
13
14
class Media extends Model implements Responsable
15
{
16
    use SortableTrait;
17
18
    const TYPE_OTHER = 'other';
19
20
    protected $table = 'media';
21
22
    protected $guarded = [];
23
24
    public function __construct(array $attributes = [])
25
    {
26
        parent::__construct($attributes);
27
28
        $this->table = config('medialibrary.table_name', 'media');
29
    }
30
31
    /**
32
     * The attributes that should be casted to native types.
33
     *
34
     * @var array
35
     */
36
    protected $casts = [
37
        'manipulations' => 'array',
38
        'custom_properties' => 'array',
39
    ];
40
41
    /**
42
     * Create the polymorphic relation.
43
     *
44
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
45
     */
46
    public function model()
47
    {
48
        return $this->morphTo();
49
    }
50
51
    /**
52
     * Get the full url to a original media file.
53
     *
54
     * @param string $conversionName
55
     *
56
     * @return string
57
     *
58
     * @throws \Spatie\MediaLibrary\Exceptions\InvalidConversion
59
     */
60
    public function getFullUrl(string $conversionName = ''): string
61
    {
62
        return url($this->getUrl($conversionName));
63
    }
64
65
    /**
66
     * Get the url to a original media file.
67
     *
68
     * @param string $conversionName
69
     *
70
     * @return string
71
     *
72
     * @throws \Spatie\MediaLibrary\Exceptions\InvalidConversion
73
     */
74
    public function getUrl(string $conversionName = ''): string
75
    {
76
        $urlGenerator = UrlGeneratorFactory::createForMedia($this, $conversionName);
77
78
        return $urlGenerator->getUrl();
79
    }
80
81
    public function getTemporaryUrl(DateTimeInterface $expiration, string $conversionName = '', array $options = []): string
82
    {
83
        $urlGenerator = UrlGeneratorFactory::createForMedia($this, $conversionName);
84
85
        return $urlGenerator->getTemporaryUrl($expiration, $options);
86
    }
87
88
    /**
89
     * Get the path to the original media file.
90
     *
91
     * @param string $conversionName
92
     *
93
     * @return string
94
     *
95
     * @throws \Spatie\MediaLibrary\Exceptions\InvalidConversion
96
     */
97
    public function getPath(string $conversionName = ''): string
98
    {
99
        $urlGenerator = UrlGeneratorFactory::createForMedia($this, $conversionName);
100
101
        return $urlGenerator->getPath();
102
    }
103
104
    /**
105
     * Collection of all ImageGenerator drivers.
106
     */
107
    public function getImageGenerators(): Collection
108
    {
109
        return collect(config('medialibrary.image_generators'));
110
    }
111
112
    /**
113
     * Determine the type of a file.
114
     *
115
     * @return string
116
     */
117
    public function getTypeAttribute()
118
    {
119
        $type = $this->getTypeFromExtension();
120
121
        if ($type !== self::TYPE_OTHER) {
122
            return $type;
123
        }
124
125
        return $this->getTypeFromMime();
126
    }
127
128
    public function getTypeFromExtension(): string
129
    {
130
        $imageGenerator = $this->getImageGenerators()
131
            ->map(function (string $className) {
132
                return app($className);
133
            })
134
            ->first->canHandleExtension(strtolower($this->extension));
135
136
        return $imageGenerator
137
            ? $imageGenerator->getType()
138
            : static::TYPE_OTHER;
139
    }
140
141
    /*
142
     * Determine the type of a file from its mime type
143
     */
144
    public function getTypeFromMime(): string
145
    {
146
        $imageGenerator = $this->getImageGenerators()
147
            ->map(function (string $className) {
148
                return app($className);
149
            })
150
            ->first->canHandleMime($this->mime_type);
151
152
        return $imageGenerator
153
            ? $imageGenerator->getType()
154
            : static::TYPE_OTHER;
155
    }
156
157
    public function getExtensionAttribute(): string
158
    {
159
        return pathinfo($this->file_name, PATHINFO_EXTENSION);
160
    }
161
162
    public function getHumanReadableSizeAttribute(): string
163
    {
164
        return File::getHumanReadableSize($this->size);
165
    }
166
167
    public function getDiskDriverName(): string
168
    {
169
        return strtolower(config("filesystems.disks.{$this->disk}.driver"));
170
    }
171
172
    /*
173
     * Determine if the media item has a custom property with the given name.
174
     */
175
    public function hasCustomProperty(string $propertyName): bool
176
    {
177
        return array_has($this->custom_properties, $propertyName);
178
    }
179
180
    /**
181
     * Get if the value of custom property with the given name.
182
     *
183
     * @param string $propertyName
184
     * @param mixed $default
185
     *
186
     * @return mixed
187
     */
188
    public function getCustomProperty(string $propertyName, $default = null)
189
    {
190
        return array_get($this->custom_properties, $propertyName, $default);
191
    }
192
193
    /**
194
     * @param string $name
195
     * @param mixed $value
196
     *
197
     * @return $this
198
     */
199
    public function setCustomProperty(string $name, $value)
200
    {
201
        $customProperties = $this->custom_properties;
202
203
        array_set($customProperties, $name, $value);
204
205
        $this->custom_properties = $customProperties;
206
207
        return $this;
208
    }
209
210
    /**
211
     * @param string $name
212
     *
213
     * @return $this
214
     */
215
    public function forgetCustomProperty(string $name)
216
    {
217
        $customProperties = $this->custom_properties;
218
219
        array_forget($customProperties, $name);
220
221
        $this->custom_properties = $customProperties;
222
223
        return $this;
224
    }
225
226
    /*
227
     * Get all the names of the registered media conversions.
228
     */
229
    public function getMediaConversionNames(): array
230
    {
231
        $conversions = ConversionCollection::createForMedia($this);
232
233
        return $conversions->map(function (Conversion $conversion) {
234
            return $conversion->getName();
235
        })->toArray();
236
    }
237
238
    /**
239
     * Create an HTTP response that represents the object.
240
     *
241
     * @param  \Illuminate\Http\Request $request
242
     *
243
     * @return \Illuminate\Http\Response
244
     */
245
    public function toResponse($request)
246
    {
247
        return response()->download($this->getPath(), $this->file_name);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->downl...h(), $this->file_name); (Symfony\Component\HttpFo...tion\BinaryFileResponse) 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...
248
    }
249
}
250