Completed
Pull Request — master (#183)
by
unknown
02:17
created

HasMediaTrait   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 296
Duplicated Lines 0 %

Coupling/Cohesion

Components 4
Dependencies 8

Importance

Changes 16
Bugs 0 Features 6
Metric Value
wmc 28
c 16
b 0
f 6
lcom 4
cbo 8
dl 0
loc 296
rs 10

16 Methods

Rating   Name   Duplication   Size   Complexity  
A bootHasMediaTrait() 0 10 2
A media() 0 4 1
A addMedia() 0 4 1
A addMediaFromUrl() 0 16 2
A copyMedia() 0 4 1
A hasMedia() 0 4 2
A getMedia() 0 4 1
A getFirstMedia() 0 6 2
A getFirstMediaUrl() 0 10 2
A getFirstMediaPath() 0 10 2
B updateMedia() 0 34 5
A removeMediaItemsNotPresentInArray() 0 10 1
A clearMediaCollection() 0 11 1
A deleteMedia() 0 14 3
A addMediaConversion() 0 8 1
A deletePreservingMedia() 0 6 1
1
<?php
2
3
namespace Spatie\MediaLibrary\HasMedia;
4
5
use Illuminate\Contracts\Events\Dispatcher;
6
use Spatie\MediaLibrary\Conversion\Conversion;
7
use Spatie\MediaLibrary\Events\CollectionHasBeenCleared;
8
use Spatie\MediaLibrary\Exceptions\MediaDoesNotBelongToModel;
9
use Spatie\MediaLibrary\Exceptions\MediaIsNotPartOfCollection;
10
use Spatie\MediaLibrary\Exceptions\UrlCouldNotBeOpened;
11
use Spatie\MediaLibrary\FileAdder\FileAdderFactory;
12
use Spatie\MediaLibrary\Filesystem;
13
use Spatie\MediaLibrary\Media;
14
use Spatie\MediaLibrary\MediaRepository;
15
16
trait HasMediaTrait
17
{
18
    /**
19
     * @var array
20
     */
21
    public $mediaConversions = [];
22
23
    /**
24
     * @var bool
25
     */
26
    private $deletePreservingMedia = false;
27
28
    public static function bootHasMediaTrait()
29
    {
30
        static::deleted(function ($entity) {
31
            if (!$entity->deletePreservingMedia) {
32
                $entity->media()->get()->map(function (Media $media) {
33
                    $media->delete();
34
                });
35
            }
36
        });
37
    }
38
39
    /**
40
     * Set the polymorphic relation.
41
     *
42
     * @return mixed
43
     */
44
    public function media()
45
    {
46
        return $this->morphMany(config('laravel-medialibrary.media_model'), 'model');
47
    }
48
49
    /**
50
     * Add a file to the medialibrary. The file will be removed from
51
     * it's original location.
52
     *
53
     * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file
54
     *
55
     * @return \Spatie\MediaLibrary\FileAdder\FileAdder
56
     */
57
    public function addMedia($file)
58
    {
59
        return app(FileAdderFactory::class)->create($this, $file);
60
    }
61
62
    /**
63
     * Add a remote file to the medialibrary.
64
     *
65
     * @param $url
66
     *
67
     * @return \Spatie\MediaLibrary\FileAdder\FileAdder
68
     *
69
     * @throws \Spatie\MediaLibrary\Exceptions\UrlCouldNotBeOpened
70
     */
71
    public function addMediaFromUrl($url)
72
    {
73
        if (!$stream = @fopen($url, 'r')) {
74
            throw new UrlCouldNotBeOpened();
75
        }
76
77
        $tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
78
        file_put_contents($tmpFile, $stream);
79
80
        $filename = basename(parse_url($url, PHP_URL_PATH));
81
82
        return app(FileAdderFactory::class)
83
            ->create($this, $tmpFile)
84
            ->usingName(pathinfo($filename, PATHINFO_FILENAME))
85
            ->usingFileName($filename);
86
    }
87
88
    /**
89
     * Copy a file to the medialibrary.
90
     *
91
     * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file
92
     *
93
     * @return \Spatie\MediaLibrary\FileAdder\FileAdder
94
     */
95
    public function copyMedia($file)
96
    {
97
        return $this->addMedia($file)->preservingOriginal();
98
    }
99
100
    /**
101
     * Determine if there is media in the given collection.
102
     *
103
     * @param $collectionName
104
     *
105
     * @return bool
106
     */
107
    public function hasMedia($collectionName = '')
108
    {
109
        return count($this->getMedia($collectionName)) ? true : false;
110
    }
111
112
    /**
113
     * Get media collection by its collectionName.
114
     *
115
     * @param string $collectionName
116
     * @param array  $filters
117
     *
118
     * @return \Illuminate\Support\Collection
119
     */
120
    public function getMedia($collectionName = '', $filters = [])
121
    {
122
        return app(MediaRepository::class)->getCollection($this, $collectionName, $filters);
123
    }
124
125
    /**
126
     * Get the first media item of a media collection.
127
     *
128
     * @param string $collectionName
129
     * @param array  $filters
130
     *
131
     * @return bool|Media
132
     */
133
    public function getFirstMedia($collectionName = 'default', $filters = [])
134
    {
135
        $media = $this->getMedia($collectionName, $filters);
136
137
        return count($media) ? $media->first() : false;
138
    }
139
140
    /**
141
     * Get the url of the image for the given conversionName
142
     * for first media for the given collectionName.
143
     * If no profile is given, return the source's url.
144
     *
145
     * @param string $collectionName
146
     * @param string $conversionName
147
     *
148
     * @return string
149
     */
150
    public function getFirstMediaUrl($collectionName = 'default', $conversionName = '')
151
    {
152
        $media = $this->getFirstMedia($collectionName);
153
154
        if (!$media) {
155
            return false;
156
        }
157
158
        return $media->getUrl($conversionName);
159
    }
160
161
    /**
162
     * Get the url of the image for the given conversionName
163
     * for first media for the given collectionName.
164
     * If no profile is given, return the source's url.
165
     *
166
     * @param string $collectionName
167
     * @param string $conversionName
168
     *
169
     * @return string
170
     */
171
    public function getFirstMediaPath($collectionName = 'default', $conversionName = '')
172
    {
173
        $media = $this->getFirstMedia($collectionName);
174
175
        if (!$media) {
176
            return false;
177
        }
178
179
        return $media->getPath($conversionName);
180
    }
181
182
    /**
183
     * Update a media collection by deleting and inserting again with new values.
184
     *
185
     * @param array  $newMediaArray
186
     * @param string $collectionName
187
     *
188
     * @return array
189
     *
190
     * @throws \Spatie\MediaLibrary\Exceptions\MediaIsNotPartOfCollection
191
     */
192
    public function updateMedia(array $newMediaArray, $collectionName = 'default')
193
    {
194
        $this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName);
195
196
        $orderColumn = 1;
197
198
        $updatedMedia = [];
199
        foreach ($newMediaArray as $newMediaItem) {
200
            $mediaClass = config('laravel-medialibrary.media_model');
201
            $currentMedia = $mediaClass::findOrFail($newMediaItem['id']);
202
203
            if ($currentMedia->collection_name != $collectionName) {
204
                throw new MediaIsNotPartOfCollection(
205
                    sprintf('Media id %s is not part of collection %s', $currentMedia->id, $collectionName)
206
                );
207
            }
208
209
            if (array_key_exists('name', $newMediaItem)) {
210
                $currentMedia->name = $newMediaItem['name'];
211
            }
212
213
            if (array_key_exists('custom_properties', $newMediaItem)) {
214
                $currentMedia->custom_properties = $newMediaItem['custom_properties'];
215
            }
216
217
            $currentMedia->order_column = $orderColumn++;
218
219
            $currentMedia->save();
220
221
            $updatedMedia[] = $currentMedia;
222
        }
223
224
        return $updatedMedia;
225
    }
226
227
    /**
228
     * @param array  $newMediaArray
229
     * @param string $collectionName
230
     */
231
    protected function removeMediaItemsNotPresentInArray(array $newMediaArray, $collectionName = 'default')
232
    {
233
        $this->getMedia($collectionName, [])
234
            ->filter(function ($currentMediaItem) use ($newMediaArray) {
235
                return !in_array($currentMediaItem->id, collect($newMediaArray)->lists('id')->toArray());
0 ignored issues
show
Deprecated Code introduced by
The method Illuminate\Support\Collection::lists() has been deprecated with message: since version 5.2. Use the "pluck" method directly.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
236
            })
237
            ->map(function ($media) {
238
                $media->delete();
239
            });
240
    }
241
242
    /**
243
     * Remove all media in the given collection.
244
     *
245
     * @param string $collectionName
246
     *
247
     * @return $this
248
     */
249
    public function clearMediaCollection($collectionName = 'default')
250
    {
251
        $this->getMedia($collectionName)->map(function ($media) {
252
            app(Filesystem::class)->removeFiles($media);
253
            $media->delete();
254
        });
255
256
        app(Dispatcher::class)->fire(new CollectionHasBeenCleared($this, $collectionName));
257
258
        return $this;
259
    }
260
261
    /**
262
     * Delete the associated media with the given id.
263
     * You may also pass a media object.
264
     *
265
     * @param int|\Spatie\MediaLibrary\Media $mediaId
266
     *
267
     * @throws \Spatie\MediaLibrary\Exceptions\MediaDoesNotBelongToModel
268
     */
269
    public function deleteMedia($mediaId)
270
    {
271
        if ($mediaId instanceof Media) {
272
            $mediaId = $mediaId->id;
273
        }
274
275
        $media = $this->media->find($mediaId);
276
277
        if (!$media) {
278
            throw new MediaDoesNotBelongToModel('Media id '.$mediaId.' does not belong to this model');
279
        }
280
281
        $media->delete();
282
    }
283
284
    /**
285
     * Add a conversion.
286
     *
287
     * @param string $name
288
     *
289
     * @return \Spatie\MediaLibrary\Conversion\Conversion
290
     */
291
    public function addMediaConversion($name)
292
    {
293
        $conversion = Conversion::create($name);
294
295
        $this->mediaConversions[] = $conversion;
296
297
        return $conversion;
298
    }
299
300
    /**
301
     * Delete the model, but preserve all the associated media.
302
     *
303
     * @return bool
304
     */
305
    public function deletePreservingMedia()
306
    {
307
        $this->deletePreservingMedia = true;
308
309
        return $this->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on Spatie\MediaLibrary\HasMedia\HasMediaTrait. Did you maybe mean deleteMedia()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
310
    }
311
}
312