Completed
Push — master ( de686d...97ea80 )
by ARCANEDEV
04:03
created

MediasController::getDefaultDiskDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php namespace Arcanesoft\Media\Http\Controllers;
2
3
use Carbon\Carbon;
4
use Illuminate\Http\Request;
5
use Illuminate\Support\Facades\Storage;
6
use Illuminate\Support\Str;
7
8
/**
9
 * Class     MediasController
10
 *
11
 * @package  Arcanesoft\Media\Http\Controllers
12
 * @author   ARCANEDEV <[email protected]>
13
 */
14
class MediasController extends Controller
15
{
16
    /* ------------------------------------------------------------------------------------------------
17
     |  Constructor
18
     | ------------------------------------------------------------------------------------------------
19
     */
20
    /**
21
     * MediasController constructor.
22
     */
23
    public function __construct()
24
    {
25
        parent::__construct();
26
27
        $this->setCurrentPage('media');
28
    }
29
30
    /* ------------------------------------------------------------------------------------------------
31
     |  Main Functions
32
     | ------------------------------------------------------------------------------------------------
33
     */
34
    public function index()
35
    {
36
        $this->setTitle('Media');
37
38
        return $this->view('manager');
39
    }
40
41
    public function getAll(Request $request)
42
    {
43
        $location = $request->get('location');
44
        $location = trim($location, '/');
45
46
        return response()->json([
47
            'status' => 'success',
48
            'data'   => array_merge(
49
                $this->getDirectoriesFromLocation($location),
50
                $this->getFilesFromLocation($location)
51
            ),
52
        ]);
53
    }
54
55
    public function uploadMedia(Request $request)
56
    {
57
        $validator = \Validator::make($request->all(), [
58
            'location' => 'required',
59
            'medias'   => 'required|array',
60
            'medias.*' => 'required|file'
61
        ]);
62
63
        if ($validator->fails()) {
64
            return response()->json(['status' => 'error', 'errors' => $validator->messages()]);
65
        }
66
67
        $location = $request->get('location');
68
69
        foreach ($request->file('medias') as $media) {
70
            /** @var \Illuminate\Http\UploadedFile  $media */
71
            $media->store($location, $this->getDefaultDiskDriver());
72
        }
73
74
        return response()->json(['status' => 'success']);
75
    }
76
77
    public function createDirectory(Request $request)
78
    {
79
        $data      = $request->all();
80
        $validator = \Validator::make($data, [
81
            'name'     => 'required', // TODO: check if the folder does not exists
82
            'location' => 'required',
83
        ]);
84
85
        $path = trim($data['location'], '/') . '/' . str_slug($data['name']);
86
87
        if ($validator->fails()) {
88
            return response()->json([
89
                'status' => 'error',
90
            ], 400);
91
        }
92
93
        $this->disk()->makeDirectory($path);
94
95
        return response()->json([
96
            'status' => 'success',
97
            'data'   => compact('path'),
98
        ]);
99
    }
100
101
    public function renameMedia(Request $request)
102
    {
103
        $data      = $request->all();
104
105
        // TODO: check if the folder does not exists
106
        $validator = \Validator::make($data, [
107
            'media'    => 'required',
108
            'newName'  => 'required',
109
            'location' => 'required',
110
        ]);
111
112
        if ($validator->fails()) {
113
            return response()->json([
114
                'status' => 'error',
115
            ], 400);
116
        }
117
118
        $location = trim($data['location'], '/');
119
        $media    = $data['media'];
120
        $src  = $location . '/' . $media['name'];
121
122
        if ($media['type'] == 'file') {
123
            $ext = pathinfo($media['url'], PATHINFO_EXTENSION);
124
            $dest = $location . '/' . Str::slug(str_replace(".{$ext}", '', $data['newName'])).'.'.$ext;
125
            $this->disk()->move($src, $dest);
126
127
            return response()->json([
128
                'status' => 'success',
129
                'data'   => ['path' => $dest],
130
            ]);
131
        }
132
        elseif ($media['type'] == 'directory') {
133
            $dest = $location . '/' . Str::slug($data['newName']);
134
            $this->disk()->move($src, $dest);
135
136
            return response()->json([
137
                'status' => 'success',
138
                'data'   => ['path' => $dest],
139
            ]);
140
        }
141
142
        return response()->json([
143
            'status'  => 'error',
144
            'message' => 'Something wrong was happened while renaming the media.',
145
        ], 400);
146
    }
147
148
    public function deleteMedia(Request $request)
149
    {
150
        // TODO: Add validation
151
        $data = $request->all();
152
153
        if ($data['media']['type'] == 'file') {
154
            $deleted = $this->disk()->delete($data['media']['path']);
155
        }
156
        else {
157
            $path = trim($data['media']['path'], '/');
158
159
            $deleted = $this->disk()->deleteDirectory($path);
160
        }
161
162
        return response()->json(['status' => $deleted ? 'success' : 'error']);
163
    }
164
165
    /* ------------------------------------------------------------------------------------------------
166
     |  Other Functions
167
     | ------------------------------------------------------------------------------------------------
168
     */
169
    /**
170
     * Get the default disk driver.
171
     *
172
     * @return \Illuminate\Filesystem\FilesystemAdapter
173
     */
174
    private function getDefaultDiskDriver()
175
    {
176
        return config('arcanesoft.media.filesystem.default');
177
    }
178
179
    /**
180
     * Get the disk adapter.
181
     *
182
     * @return \Illuminate\Filesystem\FilesystemAdapter
183
     */
184
    private function disk()
185
    {
186
        return Storage::disk($this->getDefaultDiskDriver());
187
    }
188
189
    /**
190
     * @param  string  $location
191
     *
192
     * @return array
193
     */
194
    private function getDirectoriesFromLocation($location)
195
    {
196
        return array_map(function ($directory) use ($location) {
197
            return [
198
                'name' => str_replace("$location/", '', $directory),
199
                'path' => $directory,
200
                'type' => 'directory',
201
            ];
202
        }, $this->disk()->directories($location));
203
    }
204
205
    /**
206
     * @param  string  $location
207
     *
208
     * @return array
209
     */
210
    private function getFilesFromLocation($location)
211
    {
212
        $disk   = $this->disk();
213
214
        return array_map(function ($path) use ($disk, $location) {
215
            return [
216
                'name'         => str_replace("$location/", '', $path),
217
                'type'         => 'file',
218
                'path'         => $path,
219
                'url'          => $disk->url($path),
220
                'mimetype'     => $disk->mimeType($path),
221
                'lastModified' => Carbon::createFromTimestamp($disk->lastModified($path))->toDateTimeString(),
222
                'visibility'   => $disk->getVisibility($path),
223
                'size'         => $disk->size($path),
224
            ];
225
        }, $disk->files($location));
226
    }
227
}
228