Completed
Push — master ( 072a4c...29b8f2 )
by Maarten
02:09
created

SchematicsController::modelsWithRelations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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