Complex classes like HasMediaTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use HasMediaTrait, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
23 | trait HasMediaTrait |
||
24 | { |
||
25 | /** @var array */ |
||
26 | public $mediaConversions = []; |
||
27 | |||
28 | /** @var array */ |
||
29 | public $mediaCollections = []; |
||
30 | |||
31 | /** @var bool */ |
||
32 | protected $deletePreservingMedia = false; |
||
33 | |||
34 | /** @var array */ |
||
35 | protected $unAttachedMediaLibraryItems = []; |
||
36 | |||
37 | public static function bootHasMediaTrait() |
||
38 | { |
||
39 | static::deleting(function (HasMedia $entity) { |
||
40 | if ($entity->shouldDeletePreservingMedia()) { |
||
41 | return; |
||
42 | } |
||
43 | |||
44 | if (in_array(SoftDeletes::class, trait_uses_recursive($entity))) { |
||
|
|||
45 | if (! $entity->forceDeleting) { |
||
46 | return; |
||
47 | } |
||
48 | } |
||
49 | |||
50 | $entity->media()->get()->each->delete(); |
||
51 | }); |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Set the polymorphic relation. |
||
56 | * |
||
57 | * @return mixed |
||
58 | */ |
||
59 | public function media() |
||
60 | { |
||
61 | return $this->morphMany(config('medialibrary.media_model'), 'model'); |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Add a file to the medialibrary. |
||
66 | * |
||
67 | * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file |
||
68 | * |
||
69 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder |
||
70 | */ |
||
71 | public function addMedia($file) |
||
72 | { |
||
73 | return app(FileAdderFactory::class)->create($this, $file); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Add a file from a request. |
||
78 | * |
||
79 | * @param string $key |
||
80 | * |
||
81 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder |
||
82 | */ |
||
83 | public function addMediaFromRequest(string $key) |
||
84 | { |
||
85 | return app(FileAdderFactory::class)->createFromRequest($this, $key); |
||
86 | } |
||
87 | |||
88 | /** |
||
89 | * Add multiple files from a request by keys. |
||
90 | * |
||
91 | * @param string[] $keys |
||
92 | * |
||
93 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder[] |
||
94 | */ |
||
95 | public function addMultipleMediaFromRequest(array $keys) |
||
96 | { |
||
97 | return app(FileAdderFactory::class)->createMultipleFromRequest($this, $keys); |
||
98 | } |
||
99 | |||
100 | /** |
||
101 | * Add all files from a request. |
||
102 | * |
||
103 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder[] |
||
104 | */ |
||
105 | public function addAllMediaFromRequest() |
||
106 | { |
||
107 | return app(FileAdderFactory::class)->createAllFromRequest($this); |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Add a remote file to the medialibrary. |
||
112 | * |
||
113 | * @param string $url |
||
114 | * @param string|array ...$allowedMimeTypes |
||
115 | * |
||
116 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder |
||
117 | * |
||
118 | * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded |
||
119 | */ |
||
120 | public function addMediaFromUrl(string $url, ...$allowedMimeTypes) |
||
121 | { |
||
122 | if (! $stream = @fopen($url, 'r')) { |
||
123 | throw UnreachableUrl::create($url); |
||
124 | } |
||
125 | |||
126 | $temporaryFile = tempnam(sys_get_temp_dir(), 'media-library'); |
||
127 | file_put_contents($temporaryFile, $stream); |
||
128 | |||
129 | $this->guardAgainstInvalidMimeType($temporaryFile, $allowedMimeTypes); |
||
130 | |||
131 | $filename = basename(parse_url($url, PHP_URL_PATH)); |
||
132 | |||
133 | if ($filename === '') { |
||
134 | $filename = 'file'; |
||
135 | } |
||
136 | |||
137 | $mediaExtension = explode('/', mime_content_type($temporaryFile)); |
||
138 | |||
139 | if (! str_contains($filename, '.')) { |
||
140 | $filename = "{$filename}.{$mediaExtension[1]}"; |
||
141 | } |
||
142 | |||
143 | return app(FileAdderFactory::class) |
||
144 | ->create($this, $temporaryFile) |
||
145 | ->usingName(pathinfo($filename, PATHINFO_FILENAME)) |
||
146 | ->usingFileName($filename); |
||
147 | } |
||
148 | |||
149 | /** |
||
150 | * Add a base64 encoded file to the medialibrary. |
||
151 | * |
||
152 | * @param string $base64data |
||
153 | * @param string|array ...$allowedMimeTypes |
||
154 | * |
||
155 | * @throws InvalidBase64Data |
||
156 | * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded |
||
157 | * |
||
158 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder |
||
159 | */ |
||
160 | public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): FileAdder |
||
161 | { |
||
162 | // strip out data uri scheme information (see RFC 2397) |
||
163 | if (strpos($base64data, ';base64') !== false) { |
||
164 | [$_, $base64data] = explode(';', $base64data); |
||
165 | [$_, $base64data] = explode(',', $base64data); |
||
166 | } |
||
167 | |||
168 | // strict mode filters for non-base64 alphabet characters |
||
169 | if (base64_decode($base64data, true) === false) { |
||
170 | throw InvalidBase64Data::create(); |
||
171 | } |
||
172 | |||
173 | // decoding and then reeconding should not change the data |
||
174 | if (base64_encode(base64_decode($base64data)) !== $base64data) { |
||
175 | throw InvalidBase64Data::create(); |
||
176 | } |
||
177 | |||
178 | $binaryData = base64_decode($base64data); |
||
179 | |||
180 | // temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder |
||
181 | $tmpFile = tempnam(sys_get_temp_dir(), 'medialibrary'); |
||
182 | file_put_contents($tmpFile, $binaryData); |
||
183 | |||
184 | $this->guardAgainstInvalidMimeType($tmpFile, $allowedMimeTypes); |
||
185 | |||
186 | $file = app(FileAdderFactory::class)->create($this, $tmpFile); |
||
187 | |||
188 | return $file; |
||
189 | } |
||
190 | |||
191 | /** |
||
192 | * Copy a file to the medialibrary. |
||
193 | * |
||
194 | * @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $file |
||
195 | * |
||
196 | * @return \Spatie\MediaLibrary\FileAdder\FileAdder |
||
197 | */ |
||
198 | public function copyMedia($file) |
||
199 | { |
||
200 | return $this->addMedia($file)->preservingOriginal(); |
||
201 | } |
||
202 | |||
203 | /* |
||
204 | * Determine if there is media in the given collection. |
||
205 | */ |
||
206 | public function hasMedia(string $collectionName = 'default'): bool |
||
207 | { |
||
208 | return count($this->getMedia($collectionName)) ? true : false; |
||
209 | } |
||
210 | |||
211 | /** |
||
212 | * Get media collection by its collectionName. |
||
213 | * |
||
214 | * @param string $collectionName |
||
215 | * @param array|callable $filters |
||
216 | * |
||
217 | * @return \Illuminate\Support\Collection |
||
218 | */ |
||
219 | public function getMedia(string $collectionName = 'default', $filters = []): Collection |
||
220 | { |
||
221 | return app(MediaRepository::class)->getCollection($this, $collectionName, $filters); |
||
222 | } |
||
223 | |||
224 | public function getFirstMedia(string $collectionName = 'default', array $filters = []): ?Media |
||
225 | { |
||
226 | $media = $this->getMedia($collectionName, $filters); |
||
227 | |||
228 | return $media->first(); |
||
229 | } |
||
230 | |||
231 | /* |
||
232 | * Get the url of the image for the given conversionName |
||
233 | * for first media for the given collectionName. |
||
234 | * If no profile is given, return the source's url. |
||
235 | */ |
||
236 | public function getFirstMediaUrl(string $collectionName = 'default', string $conversionName = ''): string |
||
237 | { |
||
238 | $media = $this->getFirstMedia($collectionName); |
||
239 | |||
240 | if (! $media) { |
||
241 | return ''; |
||
242 | } |
||
243 | |||
244 | return $media->getUrl($conversionName); |
||
245 | } |
||
246 | |||
247 | /* |
||
248 | * Get the url of the image for the given conversionName |
||
249 | * for first media for the given collectionName. |
||
250 | * If no profile is given, return the source's url. |
||
251 | */ |
||
252 | public function getFirstTemporaryUrl(DateTimeInterface $expiration, string $collectionName = 'default', string $conversionName = ''): string |
||
253 | { |
||
254 | $media = $this->getFirstMedia($collectionName); |
||
255 | |||
256 | if (! $media) { |
||
257 | return ''; |
||
258 | } |
||
259 | |||
260 | return $media->getTemporaryUrl($expiration, $conversionName); |
||
261 | } |
||
262 | |||
263 | /* |
||
264 | * Get the url of the image for the given conversionName |
||
265 | * for first media for the given collectionName. |
||
266 | * If no profile is given, return the source's url. |
||
267 | */ |
||
268 | public function getFirstMediaPath(string $collectionName = 'default', string $conversionName = ''): string |
||
269 | { |
||
270 | $media = $this->getFirstMedia($collectionName); |
||
271 | |||
272 | if (! $media) { |
||
273 | return ''; |
||
274 | } |
||
275 | |||
276 | return $media->getPath($conversionName); |
||
277 | } |
||
278 | |||
279 | /** |
||
280 | * Update a media collection by deleting and inserting again with new values. |
||
281 | * |
||
282 | * @param array $newMediaArray |
||
283 | * @param string $collectionName |
||
284 | * |
||
285 | * @return \Illuminate\Support\Collection |
||
286 | * |
||
287 | * @throws \Spatie\MediaLibrary\Exceptions\MediaCannotBeUpdated |
||
288 | */ |
||
289 | public function updateMedia(array $newMediaArray, string $collectionName = 'default'): Collection |
||
290 | { |
||
291 | $this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName); |
||
292 | |||
293 | return collect($newMediaArray) |
||
294 | ->map(function (array $newMediaItem) use ($collectionName) { |
||
295 | static $orderColumn = 1; |
||
296 | |||
297 | $mediaClass = config('medialibrary.media_model'); |
||
298 | $currentMedia = $mediaClass::findOrFail($newMediaItem['id']); |
||
299 | |||
300 | if ($currentMedia->collection_name !== $collectionName) { |
||
301 | throw MediaCannotBeUpdated::doesNotBelongToCollection($collectionName, $currentMedia); |
||
302 | } |
||
303 | |||
304 | if (array_key_exists('name', $newMediaItem)) { |
||
305 | $currentMedia->name = $newMediaItem['name']; |
||
306 | } |
||
307 | |||
308 | if (array_key_exists('custom_properties', $newMediaItem)) { |
||
309 | $currentMedia->custom_properties = $newMediaItem['custom_properties']; |
||
310 | } |
||
311 | |||
312 | $currentMedia->order_column = $orderColumn++; |
||
313 | |||
314 | $currentMedia->save(); |
||
315 | |||
316 | return $currentMedia; |
||
317 | }); |
||
318 | } |
||
319 | |||
320 | protected function removeMediaItemsNotPresentInArray(array $newMediaArray, string $collectionName = 'default') |
||
328 | |||
329 | /** |
||
330 | * Remove all media in the given collection. |
||
331 | * |
||
332 | * @param string $collectionName |
||
333 | * |
||
334 | * @return $this |
||
335 | */ |
||
336 | public function clearMediaCollection(string $collectionName = 'default'): self |
||
349 | |||
350 | /** |
||
351 | * Remove all media in the given collection except some. |
||
352 | * |
||
353 | * @param string $collectionName |
||
354 | * @param \Spatie\MediaLibrary\Models\Media[]|\Illuminate\Support\Collection $excludedMedia |
||
355 | * |
||
356 | * @return $this |
||
357 | */ |
||
358 | public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = []) |
||
359 | { |
||
360 | if ($excludedMedia instanceof Media) { |
||
361 | $excludedMedia = collect()->push($excludedMedia); |
||
362 | } |
||
363 | |||
364 | $excludedMedia = collect($excludedMedia); |
||
365 | |||
382 | |||
383 | /** |
||
384 | * Delete the associated media with the given id. |
||
385 | * You may also pass a media object. |
||
386 | * |
||
387 | * @param int|\Spatie\MediaLibrary\Models\Media $mediaId |
||
388 | * |
||
389 | * @throws \Spatie\MediaLibrary\Exceptions\MediaCannotBeDeleted |
||
390 | */ |
||
391 | public function deleteMedia($mediaId) |
||
405 | |||
406 | /* |
||
407 | * Add a conversion. |
||
408 | */ |
||
409 | public function addMediaConversion(string $name): Conversion |
||
417 | |||
418 | public function addMediaCollection(string $name): MediaCollection |
||
426 | |||
427 | /** |
||
428 | * Delete the model, but preserve all the associated media. |
||
429 | * |
||
430 | * @return bool |
||
431 | */ |
||
432 | public function deletePreservingMedia(): bool |
||
438 | |||
439 | /** |
||
440 | * Determines if the media files should be preserved when the media object gets deleted. |
||
441 | * |
||
442 | * @return bool |
||
443 | */ |
||
444 | public function shouldDeletePreservingMedia() |
||
448 | |||
449 | protected function mediaIsPreloaded(): bool |
||
453 | |||
454 | /** |
||
455 | * Cache the media on the object. |
||
456 | * |
||
457 | * @param string $collectionName |
||
458 | * |
||
459 | * @return mixed |
||
460 | */ |
||
461 | public function loadMedia(string $collectionName) |
||
478 | |||
479 | public function prepareToAttachMedia(Media $media, FileAdder $fileAdder) |
||
483 | |||
484 | public function processUnattachedMedia(callable $callable) |
||
492 | |||
493 | protected function guardAgainstInvalidMimeType(string $file, ...$allowedMimeTypes) |
||
510 | |||
511 | public function registerMediaConversions(Media $media = null) |
||
514 | |||
515 | public function registerMediaCollections() |
||
518 | |||
519 | public function registerAllMediaConversions(Media $media = null) |
||
542 | } |
||
543 |
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: