UploadController   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 52
c 1
b 0
f 0
wmc 10
lcom 0
cbo 6
ccs 0
cts 34
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
D formElement() 0 40 10
1
<?php
2
3
namespace Sco\Admin\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Http\UploadedFile;
7
use Illuminate\Routing\Controller;
8
use InvalidArgumentException;
9
use Sco\Admin\Contracts\ComponentInterface;
10
use Sco\Admin\Exceptions\AuthenticationException;
11
use Sco\Admin\Form\Elements\BaseFile;
12
13
class UploadController extends Controller
14
{
15
    /**
16
     * @param \Illuminate\Http\Request $request
17
     * @param \Sco\Admin\Contracts\ComponentInterface $component
18
     * @param string $field
19
     * @param mixed $id
20
     * @return \Illuminate\Http\JsonResponse
21
     * @throws \Illuminate\Validation\ValidationException
22
     * @throws \Sco\Admin\Exceptions\AuthenticationException
23
     */
24
    public function formElement(
25
        Request $request,
26
        ComponentInterface $component,
27
        $field,
28
        $id = null
29
    ) {
30
        if ((is_null($id) && ! $component->isCreate()) || ($id && ! $component->isEdit())) {
31
            throw new AuthenticationException();
32
        }
33
34
        if (! $request->hasFile($field)) {
35
            throw new InvalidArgumentException('Not found upload file');
36
        }
37
38
        $file = $request->file($field);
39
        if (is_null($file) || ! ($file instanceof UploadedFile)) {
40
            throw new InvalidArgumentException('Must be upload file');
41
        }
42
43
        if (is_null($id)) {
44
            $form = $component->fireCreate();
45
        } else {
46
            $form = $component->fireEdit($id);
47
        }
48
49
        $element = $form->getElement($field);
50
        if (! ($element instanceof BaseFile)) {
51
            throw new InvalidArgumentException(
52
                sprintf(
53
                    '[%s] element must be instanced of "%s".',
54
                    $field,
55
                    BaseFile::class
56
                )
57
            );
58
        }
59
60
        $data = $element->saveFile($file);
61
62
        return response()->json($data);
63
    }
64
}
65