Completed
Push — master ( 2507fc...48d67e )
by Maarten
01:18
created

SchematicsController::index()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Http\Controllers;
4
5
use Mtolhuys\LaravelSchematics\Actions\GenerateRelation;
6
use Mtolhuys\LaravelSchematics\Actions\RemoveRelation;
7
use Mtolhuys\LaravelSchematics\Http\Requests\NewRelationRequest;
8
use Mtolhuys\LaravelSchematics\Http\Requests\RemoveRelationRequest;
9
use Mtolhuys\LaravelSchematics\Services\ModelMapper;
10
use Mtolhuys\LaravelSchematics\Services\RelationMapper;
11
use Illuminate\Contracts\View\Factory;
12
use Illuminate\Support\Facades\Schema;
13
use Illuminate\Support\Facades\Cache;
14
use Illuminate\Routing\Controller;
15
use Illuminate\Support\Facades\DB;
16
use Illuminate\View\View;
17
use ReflectionException;
18
19
class SchematicsController extends Controller
20
{
21
    /**
22
     * @return Factory|View
23
     * @throws ReflectionException
24
     */
25
    public function index()
26
    {
27
        return view('schematics::index', $this->modelsWithRelations(
28
            ModelMapper::map()
29
        ));
30
    }
31
32
    public function removeRelation(RemoveRelationRequest $request)
33
    {
34
        (new RemoveRelation())->execute($request->all());
35
36
        Cache::forget('schematics');
37
38
        return response('Relation removed', 200);
39
    }
40
41
    public function newRelation(NewRelationRequest $request)
42
    {
43
        $relation = $request->all();
44
        $result = (new GenerateRelation())->execute($relation);
45
46
        Cache::forget('schematics');
47
48
        $relation['method']['file'] = $result->file;
49
        $relation['method']['line'] = $result->line;
50
51
        return $relation;
52
    }
53
54
    public function clearCache()
55
    {
56
        Cache::forget('schematics');
57
58
        return response('Cache cleared', 200);
59
    }
60
61
    public function details($table)
62
    {
63
         $exists = Schema::hasTable($table);
64
65
         return $exists ? DB::select(DB::raw("SHOW COLUMNS FROM {$table}")) : [];
66
    }
67
68
    /**
69
     * @param array $models
70
     * @return array
71
     * @throws ReflectionException
72
     */
73
    public function modelsWithRelations(array $models = []): array
74
    {
75
        if (Cache::has('schematics')) {
76
            return Cache::get('schematics');
77
        }
78
79
        if (empty($models)) {
80
            $models = ModelMapper::map();
81
        }
82
83
        $data = [
84
            'models' => $models,
85
            'relations' => RelationMapper::map($models),
86
        ];
87
88
        Cache::put('schematics', $data, 1440);
89
90
        return $data;
91
    }
92
}
93