• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RonasIT / laravel-media / 20292943137

17 Dec 2025 05:41AM UTC coverage: 94.231% (-0.5%) from 94.712%
20292943137

push

github

web-flow
Merge pull request #77 from RonasIT/76-change-delete-constraint

[76] change delete constraint

196 of 208 relevant lines covered (94.23%)

20.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.65
/src/Services/MediaService.php
1
<?php
2

3
namespace RonasIT\Media\Services;
4

5
use Bepsvpt\Blurhash\BlurHash;
6
use Illuminate\Http\UploadedFile;
7
use League\Flysystem\Local\LocalFilesystemAdapter;
8
use RonasIT\Media\Enums\PreviewDriverEnum;
9
use RonasIT\Media\Repositories\MediaRepository;
10
use Illuminate\Database\Eloquent\Model;
11
use Illuminate\Pagination\LengthAwarePaginator;
12
use Illuminate\Support\Facades\Auth;
13
use Illuminate\Support\Facades\Storage;
14
use RonasIT\Media\Contracts\Services\MediaServiceContract;
15
use RonasIT\Support\Services\EntityService;
16
use RonasIT\Support\Traits\FilesUploadTrait;
17
use Spatie\Image\Image;
18
use Spatie\MediaLibrary\InteractsWithMedia;
19

20
/**
21
 * @property MediaRepository $repository
22
 * @mixin MediaRepository
23
 */
24
class MediaService extends EntityService implements MediaServiceContract
25
{
26
    use FilesUploadTrait;
27
    use InteractsWithMedia;
28

29
    protected BlurHash $blurHash;
30

31
    public function __construct()
32
    {
33
        $this->setRepository(MediaRepository::class);
45✔
34
    }
35

36
    public function search(array $filters): LengthAwarePaginator
37
    {
38
        if (!Auth::check()) {
7✔
39
            $filters['is_public'] = true;
2✔
40
        } else {
41
            $filters['owner_id'] = Auth::id();
5✔
42
        }
43

44
        return $this
7✔
45
            ->searchQuery($filters)
7✔
46
            ->filterByQuery(['name'])
7✔
47
            ->getSearchResults();
7✔
48
    }
49

50
    public function create($content, string $fileName, array $data = [], PreviewDriverEnum ...$previewDrivers): Model
51
    {
52
        $fileName = $this->saveFile($fileName, $content);
6✔
53

54
        $data = $this->prepareMediaData($data, $fileName);
6✔
55

56
        if ($this->shouldCreatePreview($fileName)) {
6✔
57
            $this->createPreviews($fileName, $data, $data['owner_id'], ...$previewDrivers);
6✔
58
        }
59

60
        return $this
6✔
61
            ->repository
6✔
62
            ->create($data)
6✔
63
            ->load('preview');
6✔
64
    }
65

66
    public function bulkCreate(array $data, PreviewDriverEnum ...$previewDrivers): array
67
    {
68
        return array_map(function ($media) use ($previewDrivers) {
3✔
69
            $file = $media['file'];
3✔
70
            $content = file_get_contents($file->getPathname());
3✔
71

72
            return $this->create($content, $file->getClientOriginalName(), $media, ...$previewDrivers);
3✔
73
        }, $data);
3✔
74
    }
75

76
    public function createFromStream(UploadedFile $uploadedFile, array $data = [], PreviewDriverEnum ...$previewDrivers): Model
77
    {
78
        $filePath = Storage::putFile('', $uploadedFile);
23✔
79

80
        $data = $this->prepareMediaData($data, $filePath);
23✔
81

82
        if ($this->shouldCreatePreview($filePath)) {
23✔
83
            $this->createPreviews($filePath, $data, $data['owner_id'], ...$previewDrivers);
22✔
84
        }
85

86
        return $this
23✔
87
            ->repository
23✔
88
            ->create($data)
23✔
89
            ->load('preview');
23✔
90
    }
91

92
    public function delete($where): int
93
    {
94
        $entity = $this->first($where);
3✔
95

96
        if (!empty($entity->preview_id)) {
3✔
97
            $this->delete($entity->preview_id);
×
98
        }
99

100
        Storage::delete($entity->name);
3✔
101

102
        return $this->repository->delete($where);
3✔
103
    }
104

105
    public function first(array|int $where = []): ?Model
106
    {
107
        return $this->repository->first($where);
9✔
108
    }
109

110
    protected function createFilePreview(string $filename, ?int $ownerId = null): Model
111
    {
112
        $this->createTempDir(Storage::disk('local')->path('temp_files'));
27✔
113

114
        $filePath = Storage::path($filename);
27✔
115
        $previewFilename = "preview_{$filename}";
27✔
116
        $tempPreviewFilePath = "/temp_files/{$previewFilename}";
27✔
117

118
        $tempFilePath = "/temp_files/{$filename}";
27✔
119

120
        $content = Storage::get($filename);
27✔
121

122
        if (!$this->isLocalStorageUsing()) {
27✔
123
            Storage::disk('local')->put($tempFilePath, $content);
×
124

125
            $filePath = Storage::disk('local')->path($tempFilePath);
×
126
        }
127

128
        Image::load($filePath)
27✔
129
            ->width(config('media.preview.width'))
27✔
130
            ->height(config('media.preview.height'))
27✔
131
            ->save(Storage::disk('local')->path($tempPreviewFilePath));
27✔
132

133
        Storage::put($previewFilename, Storage::disk('local')->get($tempPreviewFilePath));
27✔
134

135
        if (!$this->isLocalStorageUsing()) {
27✔
136
            Storage::disk('local')->delete(Storage::path($tempFilePath));
×
137
        }
138

139
        Storage::disk('local')->delete($tempPreviewFilePath);
27✔
140

141
        $data['name'] = $previewFilename;
27✔
142
        $data['link'] = Storage::url($previewFilename);
27✔
143
        $data['owner_id'] = $ownerId;
27✔
144

145
        return $this->repository->create($data);
27✔
146
    }
147

148
    private function isLocalStorageUsing(): bool
149
    {
150
        return Storage::getAdapter() instanceof (LocalFilesystemAdapter::class);
27✔
151
    }
152

153
    protected function createTempDir(string $name): void
154
    {
155
        if (!is_dir($name)) {
27✔
156
            mkdir(
27✔
157
                directory: $name,
27✔
158
                recursive: true,
27✔
159
            );
27✔
160
        }
161
    }
162

163
    protected function createHashPreview(string $fileName): string
164
    {
165
        $localStorage = Storage::disk('local');
4✔
166

167
        $tmpFilename = "tmp_{$fileName}";
4✔
168

169
        $localStorage->put($tmpFilename, Storage::get($fileName));
4✔
170

171
        $blurHash = $this
4✔
172
            ->getBlurHashEncoder()
4✔
173
            ->encode($localStorage->path($tmpFilename));
4✔
174

175
        $localStorage->delete($tmpFilename);
4✔
176

177
       return $blurHash;
4✔
178
    }
179

180
    protected function getBlurHashEncoder(): BlurHash
181
    {
182
        return $this->blurHash ??= new BlurHash(
4✔
183
            config('blurhash.driver'),
4✔
184
            config('blurhash.components-x'),
4✔
185
            config('blurhash.components-y'),
4✔
186
            config('blurhash.resized-max-size'),
4✔
187
        );
4✔
188
    }
189

190
    protected function createPreviews(string $fileName, array &$data, int $ownerId = null, PreviewDriverEnum ...$previewTypes): void
191
    {
192
        if (empty($previewTypes)) {
28✔
193
            $previewTypes = config('media.drivers');
23✔
194
        }
195

196
        foreach ($previewTypes as $type) {
28✔
197
            if ($type === PreviewDriverEnum::File) {
28✔
198
                $preview = $this->createFilePreview($fileName, $ownerId);
27✔
199

200
                $data['preview_id'] = $preview->id;
27✔
201
            }
202

203
            if ($type === PreviewDriverEnum::Hash) {
28✔
204
                $data['blur_hash'] = $this->createHashPreview($fileName);
4✔
205
            }
206
        }
207
    }
208

209
    protected function prepareMediaData(array $data, string $filePath): array
210
    {
211
        if (empty($data['owner_id'])) {
29✔
212
            $user = Auth::user();
26✔
213

214
            $isUserModel = (!empty($user) && get_class($user) === config('media.classes.user_model'));
26✔
215

216
            $data['owner_id'] = when($isUserModel, fn () => $user->getAuthIdentifier());
26✔
217
        }
218

219
        $data['name'] = $filePath;
29✔
220
        $data['link'] = Storage::url($data['name']);
29✔
221

222
        return $data;
29✔
223
    }
224

225
    protected function shouldCreatePreview(string $fileName): bool
226
    {
227
        return str_starts_with(Storage::mimeType($fileName), 'image');
29✔
228
    }
229
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc