Completed
Push — master ( bdd975...317c15 )
by CodexShaper
05:13
created

Manager::generateModelName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 2
rs 10
1
<?php
2
namespace CodexShaper\DBM;
3
4
use CodexShaper\DBM\Facades\Driver;
5
use CodexShaper\DBM\Models\DBM_Field;
6
use CodexShaper\DBM\Models\DBM_MongoField;
7
use CodexShaper\DBM\Models\DBM_MongoObject;
8
use CodexShaper\DBM\Models\DBM_MongoPermission;
9
use CodexShaper\DBM\Models\DBM_MongoTemplate;
10
use CodexShaper\DBM\Models\DBM_Object;
11
use CodexShaper\DBM\Models\DBM_Permission;
12
use CodexShaper\DBM\Models\DBM_Template;
13
use Illuminate\Filesystem\Filesystem;
14
use Illuminate\Support\Facades\App;
15
use Illuminate\Support\Facades\Artisan;
16
use Illuminate\Support\Facades\Auth;
17
use Illuminate\Support\Facades\File;
18
use Illuminate\Support\Facades\Response;
19
use Illuminate\Support\Facades\Route;
20
use Illuminate\Support\Facades\Storage;
21
use Illuminate\Support\Str;
22
23
class Manager
24
{
25
    public function webRoutes()
26
    {
27
        require __DIR__ . '/../routes/web.php';
28
    }
29
30
    public function apiRoutes()
31
    {
32
        require __DIR__ . '/../routes/api.php';
33
    }
34
35
    /**
36
     * Load assests
37
     *
38
     * @param  string $path
39
     *
40
     * @return \Illuminate\Http\Response
41
     */
42
    public function assets($path)
43
    {
44
        $file = base_path(trim(config('dbm.resources_path'), '/') . "/" . urldecode($path));
45
46
        if (File::exists($file)) {
47
48
            switch ($extension = pathinfo($file, PATHINFO_EXTENSION)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $extension is dead and can be removed.
Loading history...
49
                case 'js':
50
                    $mimeType = 'text/javascript';
51
                    break;
52
                case 'css':
53
                    $mimeType = 'text/css';
54
                    break;
55
                default:
56
                    $mimeType = File::mimeType($file);
57
                    break;
58
            }
59
60
            if (!$mimeType) {
61
                $mimeType = 'text/plain';
62
            }
63
64
            $response = Response::make(File::get($file), 200);
65
            $response->header('Content-Type', $mimeType);
66
            $response->setSharedMaxAge(31536000);
67
            $response->setMaxAge(31536000);
68
            $response->setExpires(new \DateTime('+1 year'));
69
70
            return $response;
71
        }
72
73
        return response('', 404);
74
    }
75
76
    public function getModelNamespace()
77
    {
78
        return trim(config('dbm.modal_namespace', App::getNamespace()), '\\');
79
    }
80
81
    public function generateModelName($className)
82
    {
83
        $namespace = static::getModelNamespace();
0 ignored issues
show
Bug Best Practice introduced by
The method CodexShaper\DBM\Manager::getModelNamespace() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

83
        /** @scrutinizer ignore-call */ 
84
        $namespace = static::getModelNamespace();
Loading history...
84
85
        $modelName = ucfirst(Str::singular($className));
86
87
        return $namespace . '\\' . $modelName;
88
    }
89
90
    public function makeModel($model, $table)
91
    {
92
        try {
93
94
            $partials = explode("\\", $model);
95
96
            $className = array_pop($partials);
97
            $namespace = implode("\\", $partials);
98
99
            $contents = "<?php\n\n";
100
            $contents .= "namespace " . $namespace . ";\n\n";
101
            if (Driver::isMongoDB()) {
102
                $contents .= "use Jenssegers\Mongodb\Eloquent\Model;\n\n";
103
            } else {
104
                $contents .= "use Illuminate\Database\Eloquent\Model;\n\n";
105
            }
106
            $contents .= "class " . $className . " extends Model\n";
107
            $contents .= "{\n\n";
108
            if (Driver::isMongoDB()) {
109
                $contents .= "\tprotected \$collection = '" . $table . "';\n";
110
            } else {
111
                $contents .= "\tprotected \$table = '" . $table . "';\n";
112
            }
113
114
            // $content .= "\tpublic \$timestamps = false;\n";
115
            $contents .= "}\n";
116
117
            $filesystem = new Filesystem;
118
            $filesystem->put(base_path($model . ".php"), $contents);
119
        } catch (\Exception $e) {
120
            throw new \Exception("There has an error when create model. The error is :" . $e->getMessage(), 1);
121
122
        }
123
124
    }
125
126
    public function makeController($controller)
127
    {
128
        try {
129
            Artisan::call('make:controller', [
130
                'name' => $controller,
131
            ]);
132
        } catch (\Exception $e) {
133
            throw new \Exception("There has an error when create Controller. The error is :" . $e->getMessage(), 1);
134
135
        }
136
137
    }
138
139
    public function model($model, $table = null)
140
    {
141
        if ($table == null) {
142
            return new $model;
143
        }
144
145
        return (new $model)->setTable($table);
146
    }
147
148
    public function Object()
149
    {
150
        if (Driver::isMongoDB()) {
151
            return new DBM_MongoObject();
152
        }
153
154
        return new DBM_Object;
155
    }
156
157
    public function Field()
158
    {
159
        if (Driver::isMongoDB()) {
160
            return new DBM_MongoField;
161
        }
162
163
        return new DBM_Field;
164
    }
165
166
    public function Permission()
167
    {
168
        if (Driver::isMongoDB()) {
169
            return new DBM_MongoPermission;
170
        }
171
172
        return new DBM_Permission;
173
    }
174
175
    public function Template()
176
    {
177
        if (Driver::isMongoDB()) {
178
            return new DBM_MongoTemplate;
179
        }
180
181
        return new DBM_Template;
182
    }
183
184
    public function templates()
185
    {
186
        $templates    = static::Template()->get();
0 ignored issues
show
Bug Best Practice introduced by
The method CodexShaper\DBM\Manager::Template() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

186
        $templates    = static::/** @scrutinizer ignore-call */ Template()->get();
Loading history...
187
        $newTemplates = [];
188
189
        foreach ($templates as $template) {
190
            $newTemplates[] = (object) [
191
                "name"          => $template->name,
192
                "oldName"       => $template->old_name,
193
                "type"          => [
194
                    "name" => $template->type,
195
                ],
196
                "notnull"       => $template->notnull,
197
                "unsigned"      => $template->unsigned,
198
                "autoincrement" => $template->auto_increment,
199
                "default"       => $template->default,
200
                "length"        => $template->length,
201
                "index"         => ($template->index != null) ? $template->index : "",
202
            ];
203
        }
204
205
        return $newTemplates;
206
    }
207
208
    /*
209
     * File System
210
     */
211
212
    public function getPathPrefix($driver = 'local')
213
    {
214
        return trim(Storage::disk($driver)->getDriver()->getAdapter()->getPathPrefix(), DIRECTORY_SEPARATOR);
215
    }
216
217
    /*
218
     * Permission
219
     */
220
221
    public function userPermissions()
222
    {
223
        $user = Auth::user();
224
225
        return self::Object()
0 ignored issues
show
Bug Best Practice introduced by
The method CodexShaper\DBM\Manager::Object() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
        return self::/** @scrutinizer ignore-call */ Object()
Loading history...
226
            ->setManyToManyRelation(
227
                $user,
228
                static::Permission(),
0 ignored issues
show
Bug Best Practice introduced by
The method CodexShaper\DBM\Manager::Permission() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

228
                static::/** @scrutinizer ignore-call */ 
229
                        Permission(),
Loading history...
229
                'dbm_user_permissions',
230
                'user_id',
231
                'dbm_permission_id'
232
            )
233
            ->belongs_to_many;
0 ignored issues
show
Bug introduced by
The property belongs_to_many does not seem to exist on CodexShaper\DBM\Models\DBM_Object. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
234
    }
235
236
    public function isLoggedIn()
237
    {
238
        if (Auth::guest()) {
239
            return Route::has('login') ? redirect(route('login')) : Response::view('dbm::errors.404', [], 404);
240
        }
241
242
        return true;
243
    }
244
245
    public function checkPermission($prefix, $slug)
246
    {
247
        if (Auth::guest()) {
248
            return 'not_logged_in';
249
        }
250
251
        $user_model        = config('dbm.user.model');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_model is dead and can be removed.
Loading history...
252
        $user_table        = config('dbm.user.table');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_table is dead and can be removed.
Loading history...
253
        $user_local_key    = config('dbm.user.local_key');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_local_key is dead and can be removed.
Loading history...
254
        $user_display_name = config('dbm.user.display_name');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_display_name is dead and can be removed.
Loading history...
255
256
        $permissions = $this->userPermissions();
257
258
        foreach ($permissions as $permission) {
259
            if ($permission->prefix == $prefix && $permission->slug == $slug) {
260
                return 'authorized';
261
            }
262
        }
263
264
        return 'not_authorized';
265
266
    }
267
268
    public function authorize($permission)
269
    {
270
        $permission = explode('.', $permission);
271
272
        $prefix = $permission[0];
273
        $slug   = $permission[1];
274
275
        switch ($this->checkPermission($prefix, $slug)) {
276
            case 'not_logged_in':
277
                return response()->json([
278
                    'success' => false,
279
                    'url'     => route('login'),
280
                ]);
281
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
282
283
            case 'not_authorized':
284
                return response()->json([
285
                    'success' => false,
286
                    'errors'  => ["You don't have permission to " . $slug . " " . $prefix],
287
                ], 401);
288
                break;
289
            case 'authorized':
290
                return true;
291
                break;
292
        }
293
    }
294
295
}
296