ExtensionRule::validateMediaItem()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 15
rs 10
1
<?php
2
3
namespace Spatie\MediaLibraryPro\Rules\ItemRules;
4
5
use Illuminate\Support\Arr;
6
use Symfony\Component\Mime\MimeTypes;
7
8
class ExtensionRule extends MediaItemRule
9
{
10
    protected array $allowedExtensions;
11
12
    /** @var string|array */
13
    public function __construct($allowedExtensions)
14
    {
15
        $this->allowedExtensions = Arr::wrap($allowedExtensions);
16
    }
17
18
    public function validateMediaItem(): bool
19
    {
20
        if (! $media = $this->getTemporaryUploadMedia()) {
21
            return true;
22
        }
23
24
        if (empty($media->mime_type)) {
25
            $extension = pathinfo($media->file_name, PATHINFO_EXTENSION);
26
27
            return in_array($extension, $this->allowedExtensions);
28
        }
29
30
        $actualExtensions = (new MimeTypes())->getExtensions($media->mime_type);
31
32
        return count(array_intersect($actualExtensions, $this->allowedExtensions)) > 0;
33
    }
34
35
    public function message()
36
    {
37
        return __('media-library::validation.extension', [
38
            'extensions' => implode(', ', $this->allowedExtensions),
39
        ]);
40
    }
41
}
42