Passed
Push — master ( afb865...5313f5 )
by Reza
03:19
created

Create::create()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 21
c 1
b 0
f 0
nc 7
nop 0
dl 0
loc 37
rs 9.2728
1
<?php
2
3
namespace EasyPanel\Http\Livewire\CRUD;
4
5
use Livewire\Component;
6
use EasyPanel\Models\CRUD;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Facades\Artisan;
9
10
class Create extends Component
11
{
12
13
    public $model;
14
    public $route;
15
16
    protected $rules = [
17
        'model' => 'required|min:8|unique:cruds',
18
        'route' => 'required|min:2|unique:cruds',
19
    ];
20
21
    public function updated($input)
22
    {
23
        $this->validateOnly($input);
24
    }
25
26
    public function create()
27
    {
28
        $this->validate();
29
30
        if (!class_exists($this->model) or ! app()->make($this->model) instanceof Model){
31
            $this->addError('model', __('Namespace is invalid'));
32
33
            return;
34
        }
35
36
        if (!preg_match('/^([a-z]|[0-9])+/', $this->route)){
37
            $this->addError('route', __('Route is invalid'));
38
39
            return;
40
        }
41
42
        try{
43
            $name = strtolower($this->getModelName($this->model));
44
            CRUD::create([
45
                'model' => trim($this->model, '\\'),
46
                'name' => $name,
47
                'route' => trim($this->route, '\\'),
48
            ]);
49
50
            Artisan::call('panel:config', [
51
                'name' => $name,
52
                '--force' => true
53
            ]);
54
55
            $this->dispatchBrowserEvent('show-message', ['type' => 'success', 'message' => __('CreatedMessage', ['name' => __('CRUD') ])]);
56
        } catch(\Exception $exception){
57
            $this->dispatchBrowserEvent('show-message', ['type' => 'error', 'message' => __('UnknownError') ]);
58
        }
59
60
61
        $this->emit('crudUpdated');
62
        $this->reset();
63
    }
64
65
    public function render()
66
    {
67
        return view('admin::livewire.crud.create')
68
            ->layout('admin::layouts.app');
69
    }
70
71
    private function getModelName($model){
72
        $model = explode('\\', $model);
73
74
        return end($model);
75
    }
76
}
77