Completed
Pull Request — master (#38)
by Philippe
05:00
created

AssetLibrary::remove()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 16
rs 9.6111
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Illuminate\Support\Collection;
6
7
class AssetLibrary
8
{
9
    /**
10
     * Removes one or more assets by their ids.
11
     */
12
    public static function removeByIds($imageIds)
13
    {
14
        if (is_array($imageIds)) {
15
            foreach ($imageIds as $id) {
16
                self::remove($id);
17
            }
18
        } else {
19
            if (! $imageIds) {
20
                return;
21
            }
22
23
            self::remove($imageIds);
24
        }
25
    }
26
27
    /**
28
     * Removes one assets by id.
29
     * It also checks if you have the permissions to remove the file.
30
     *
31
     * @param $imageIds
32
     */
33
    public static function remove($id)
34
    {
35
        if (! $id) {
36
            return false;
37
        }
38
39
        $asset = Asset::find($id)->first();
40
        $media = $asset->media;
41
42
        foreach ($media as $file) {
43
            if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
44
                return;
45
            }
46
        }
47
48
        $asset->delete();
49
    }
50
51
    /**
52
     * Returns a collection of all the assets in the library.
53
     * @return \Illuminate\Support\Collection
54
     */
55
    public static function getAllAssets(): Collection
56
    {
57
        return Asset::all()->sortByDesc('created_at');
58
    }
59
}
60