Passed
Push — master ( 0e891d...e9b6b0 )
by CodexShaper
05:21
created

Manager::checkPermission()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 20
ccs 0
cts 16
cp 0
crap 30
rs 9.6111
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
    /**
26
     * Include Web routes
27
     *
28
     * @return void
29
     */
30
    public function webRoutes()
31
    {
32
        require __DIR__ . '/../routes/web.php';
33
    }
34
    /**
35
     * Include API routes
36
     *
37
     * @return void
38
     */
39
    public function apiRoutes()
40
    {
41
        require __DIR__ . '/../routes/api.php';
42
    }
43
44
    /**
45
     * Load assests
46
     *
47
     * @param  string $path
48
     *
49
     * @return \Illuminate\Http\Response
50
     */
51
    public function assets($path)
52
    {
53
        $file = base_path(trim(config('dbm.resources_path'), '/') . "/" . urldecode($path));
54
55
        if (File::exists($file)) {
56
57
            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...
58
                case 'js':
59
                    $mimeType = 'text/javascript';
60
                    break;
61
                case 'css':
62
                    $mimeType = 'text/css';
63
                    break;
64
                default:
65
                    $mimeType = File::mimeType($file);
66
                    break;
67
            }
68
69
            if (!$mimeType) {
70
                $mimeType = 'text/plain';
71
            }
72
73
            $response = Response::make(File::get($file), 200);
74
            $response->header('Content-Type', $mimeType);
75
            $response->setSharedMaxAge(31536000);
76
            $response->setMaxAge(31536000);
77
            $response->setExpires(new \DateTime('+1 year'));
78
79
            return $response;
80
        }
81
82
        return response('', 404);
83
    }
84
    /**
85
     * Get Model Namespace
86
     *
87
     * @return string
88
     */
89
    public function getModelNamespace()
90
    {
91
        return trim(config('dbm.modal_namespace', App::getNamespace()), '\\');
92
    }
93
    /**
94
     * Get model name with namespace
95
     *
96
     * @param string $className
97
     *
98
     * @return string
99
     */
100
    public function generateModelName($className)
101
    {
102
        return static::getModelNamespace() . '\\' . ucfirst(Str::singular($className));
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

102
        return static::/** @scrutinizer ignore-call */ getModelNamespace() . '\\' . ucfirst(Str::singular($className));
Loading history...
103
    }
104
    /**
105
     * Make new model
106
     *
107
     * @param string $model
108
     * @param string $table
109
     *
110
     * @return void
111
     */
112
    public function makeModel($model, $table)
113
    {
114
        try {
115
116
            $partials  = explode("\\", $model);
117
            $className = array_pop($partials);
118
            $namespace = implode("\\", $partials);
119
120
            $app       = array_shift($partials);
121
            $directory = implode(DIRECTORY_SEPARATOR, $partials);
122
            if (strtolower($app) != 'app') {
123
                $namespace = "App\\" . $namespace;
124
                $directory = $app . DIRECTORY_SEPARATOR . $directory;
125
            }
126
127
            $path = app_path() . DIRECTORY_SEPARATOR . $directory;
128
129
            if (!File::isDirectory($path)) {
130
                File::makeDirectory($path, 0777, true, true);
131
            }
132
133
            $contents = "<?php\n\n";
134
            $contents .= "namespace " . $namespace . ";\n\n";
135
            if (Driver::isMongoDB()) {
136
                $contents .= "use Jenssegers\Mongodb\Eloquent\Model;\n\n";
137
            } else {
138
                $contents .= "use Illuminate\Database\Eloquent\Model;\n\n";
139
            }
140
            $contents .= "class " . $className . " extends Model\n";
141
            $contents .= "{\n\n";
142
            if (Driver::isMongoDB()) {
143
                $contents .= "\tprotected \$collection = '" . $table . "';\n";
144
            } else {
145
                $contents .= "\tprotected \$table = '" . $table . "';\n";
146
            }
147
148
            // $content .= "\tpublic \$timestamps = false;\n";
149
            $contents .= "}\n";
150
151
            $filesystem = new Filesystem;
152
            $filesystem->put($path . DIRECTORY_SEPARATOR . $className . ".php", $contents);
153
154
        } catch (\Exception $e) {
155
            throw new \Exception("There has an error when create model. The error is :" . $e->getMessage(), 1);
156
157
        }
158
159
    }
160
    /**
161
     * Make new controller
162
     *
163
     * @param string $controller
164
     *
165
     * @return void
166
     */
167
    public function makeController($controller)
168
    {
169
        try {
170
            Artisan::call('make:controller', [
171
                'name' => $controller,
172
            ]);
173
        } catch (\Exception $e) {
174
            throw new \Exception("There has an error when create Controller. The error is :" . $e->getMessage(), 1);
175
176
        }
177
178
    }
179
    /**
180
     * Create new model instance
181
     *
182
     * @param string $model
183
     * @param string|null $table
184
     *
185
     * @return object
186
     */
187
    public function model($model, $table = null)
188
    {
189
        if ($table == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $table of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
190
            return new $model;
191
        }
192
193
        return (new $model)->setTable($table);
194
    }
195
    /**
196
     * Create new model instance
197
     *
198
     * @return \CodexShaper\DBM\Models\DBM_MongoObject|\CodexShaper\DBM\Models\DBM_Object
199
     */
200
    public function Object()
201
    {
202
        if (Driver::isMongoDB()) {
203
            return new DBM_MongoObject();
204
        }
205
206
        return new DBM_Object;
207
    }
208
    /**
209
     * Create new model instance
210
     *
211
     * @return \CodexShaper\DBM\Models\DBM_MongoField|\CodexShaper\DBM\Models\DBM_Field
212
     */
213
    public function Field()
214
    {
215
        if (Driver::isMongoDB()) {
216
            return new DBM_MongoField;
217
        }
218
219
        return new DBM_Field;
220
    }
221
    /**
222
     * Create new model instance
223
     *
224
     * @return \CodexShaper\DBM\Models\DBM_MongoPermission|\CodexShaper\DBM\Models\DBM_Permission
225
     */
226
    public function Permission()
227
    {
228
        if (Driver::isMongoDB()) {
229
            return new DBM_MongoPermission;
230
        }
231
232
        return new DBM_Permission;
233
    }
234
    /**
235
     * Create new model instance
236
     *
237
     * @return \CodexShaper\DBM\Models\DBM_MongoTemplate|\CodexShaper\DBM\Models\DBM_Template
238
     */
239
    public function Template()
240
    {
241
        if (Driver::isMongoDB()) {
242
            return new DBM_MongoTemplate;
243
        }
244
245
        return new DBM_Template;
246
    }
247
    /**
248
     * Get all templates
249
     *
250
     * @return array
251
     */
252
    public function templates()
253
    {
254
        $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

254
        $templates    = static::/** @scrutinizer ignore-call */ Template()->get();
Loading history...
255
        $newTemplates = [];
256
257
        foreach ($templates as $template) {
258
            $newTemplates[] = (object) [
259
                "name"          => $template->name,
260
                "oldName"       => $template->old_name,
261
                "type"          => [
262
                    "name" => $template->type,
263
                ],
264
                "notnull"       => $template->notnull,
265
                "unsigned"      => $template->unsigned,
266
                "autoincrement" => $template->auto_increment,
267
                "default"       => $template->default,
268
                "length"        => $template->length,
269
                "index"         => ($template->index != null) ? $template->index : "",
270
            ];
271
        }
272
273
        return $newTemplates;
274
    }
275
    /**
276
     * Get file path prefix
277
     *
278
     * @param string @driver
0 ignored issues
show
Documentation Bug introduced by
The doc comment @driver at position 0 could not be parsed: Unknown type name '@driver' at position 0 in @driver.
Loading history...
279
     *
280
     * @return string
281
     */
282
    public function getPathPrefix($driver = 'local')
283
    {
284
        return trim(Storage::disk($driver)->getDriver()->getAdapter()->getPathPrefix(), DIRECTORY_SEPARATOR);
285
    }
286
    /**
287
     * Get all templates
288
     *
289
     * @return \Illuminate\Support\Collection
290
     */
291
    public function userPermissions()
292
    {
293
        $user = Auth::user();
294
295
        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

295
        return self::/** @scrutinizer ignore-call */ Object()
Loading history...
296
            ->setManyToManyRelation(
297
                $user,
298
                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

298
                static::/** @scrutinizer ignore-call */ 
299
                        Permission(),
Loading history...
299
                'dbm_user_permissions',
300
                'user_id',
301
                'dbm_permission_id'
302
            )
303
            ->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...
304
    }
305
    /**
306
     * Check user loggedin or not
307
     *
308
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\View\View
309
     */
310
    public function isLoggedIn()
311
    {
312
        if (Auth::guest()) {
313
            return Route::has('login') ? redirect(route('login')) : Response::view('dbm::errors.404', [], 404);
314
        }
315
316
        return true;
317
    }
318
    /**
319
     * Check user permission
320
     *
321
     * @param string $prefix
322
     * @param string $slug
323
     *
324
     * @return string
325
     */
326
    public function checkPermission($prefix, $slug)
327
    {
328
        if (Auth::guest()) {
329
            return 'not_logged_in';
330
        }
331
332
        $user_model        = config('dbm.auth.user.model');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_model is dead and can be removed.
Loading history...
333
        $user_table        = config('dbm.auth.user.table');
0 ignored issues
show
Unused Code introduced by
The assignment to $user_table is dead and can be removed.
Loading history...
334
        $user_local_key    = config('dbm.auth.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...
335
        $user_display_name = config('dbm.auth.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...
336
337
        $permissions = $this->userPermissions();
338
339
        foreach ($permissions as $permission) {
340
            if ($permission->prefix == $prefix && $permission->slug == $slug) {
341
                return 'authorized';
342
            }
343
        }
344
345
        return 'not_authorized';
346
347
    }
348
    public function authorize($permission)
349
    {
350
        $permission = explode('.', $permission);
351
352
        $prefix = $permission[0];
353
        $slug   = $permission[1];
354
355
        switch ($this->checkPermission($prefix, $slug)) {
356
            case 'not_logged_in':
357
                return response()->json([
358
                    'success' => false,
359
                    'url'     => route('login'),
360
                ]);
361
                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...
362
363
            case 'not_authorized':
364
                return response()->json([
365
                    'success' => false,
366
                    'errors'  => ["You don't have permission to " . $slug . " " . $prefix],
367
                ], 401);
368
                break;
369
            case 'authorized':
370
                return true;
371
                break;
372
        }
373
    }
374
375
}
376