Completed
Push — master ( 7eba8f...c52d76 )
by Iman
18s queued 10s
created

IndexImport::readAndInsert()   C

Complexity

Conditions 9
Paths 27

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 31
c 0
b 0
f 0
nc 27
nop 3
dl 0
loc 51
rs 6.2727

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace crocodicstudio\crudbooster\controllers\Helpers;
4
5
use CRUDBooster;
0 ignored issues
show
Bug introduced by
The type CRUDBooster was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Illuminate\Support\Facades\Storage;
7
use Illuminate\Support\Facades\Validator;
8
use Maatwebsite\Excel\Facades\Excel;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Facades\Cache;
11
12
13
class IndexImport
14
{
15
    /**
16
     * @return mixed
17
     */
18
    public function doneImport()
19
    {
20
        $data = [];
21
        $data['page_title'] = trans('crudbooster.import_page_title', ['module' => \CRUDBooster::getCurrentModule()->name]);
22
        session()->put('select_column', request('select_column'));
23
24
        return view('crudbooster::import', $data);
25
    }
26
27
28
    /**
29
     * @param $file_md5
30
     * @return mixed
31
     */
32
    function handleImportProgress($file_md5)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
33
    {
34
        $total = session('total_data_import') * 100;
35
        $prog = intval(cache('success_'.$file_md5)) / $total;
36
        $prog = round($prog, 2);
37
38
        if ($prog >= 100) {
39
            cache()->forget('success_'.$file_md5);
40
        }
41
42
        return response()->json(['progress' => $prog, 'last_error' => cache('error_'.$file_md5)]);
0 ignored issues
show
Bug introduced by
The method json() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

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

42
        return response()->/** @scrutinizer ignore-call */ json(['progress' => $prog, 'last_error' => cache('error_'.$file_md5)]);
Loading history...
43
    }
44
45
    /**
46
     * @param $file
47
     * @return string
48
     */
49
    function uploadImportData($file)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
50
    {
51
        $dir = 'uploads/'.date('Y-m');
52
        $filename = md5(str_random(5)).'.'. $file->getClientOriginalExtension();
53
54
        //Create Directory Monthly
55
        Storage::makeDirectory($dir);
56
57
        //Move file to storage
58
        Storage::putFileAs($dir, $file, $filename);
59
60
        return CRUDBooster::mainpath('import-data').'?file='.base64_encode($dir.'/'.$filename);
61
    }
62
63
    /**
64
     * @param $file
65
     * @return array
66
     */
67
    function validateForImport($file)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
68
    {
69
        return Validator::make(['extension' => $file->getClientOriginalExtension(),], ['extension' => 'in:xls,xlsx,csv']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Illuminate\Suppor... => 'in:xls,xlsx,csv')) returns the type Illuminate\Contracts\Validation\Validator which is incompatible with the documented return type array.
Loading history...
70
    }
71
72
73
    /**
74
     * @param $file_md5
75
     * @param $table
76
     * @param $titleField
77
     */
78
    function InsertToDB($file_md5, $table, $titleField)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
79
    {
80
        $select_column = array_filter(session('select_column'));
0 ignored issues
show
Bug introduced by
It seems like session('select_column') can also be of type Illuminate\Session\Store and Illuminate\Session\SessionManager; however, parameter $input of array_filter() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

80
        $select_column = array_filter(/** @scrutinizer ignore-type */ session('select_column'));
Loading history...
81
        $table_columns = DB::getSchemaBuilder()->getColumnListing($table);
82
83
        $file = base64_decode(request('file'));
0 ignored issues
show
Bug introduced by
It seems like request('file') can also be of type array; however, parameter $data of base64_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

83
        $file = base64_decode(/** @scrutinizer ignore-type */ request('file'));
Loading history...
84
        $file = 'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.$file;
85
        $rows = Excel::load($file, function ($reader) {
0 ignored issues
show
Unused Code introduced by
The parameter $reader is not used and could be removed. ( Ignorable by Annotation )

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

85
        $rows = Excel::load($file, function (/** @scrutinizer ignore-unused */ $reader) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
86
        })->get();
87
88
        //$data_import_column = [];
89
        foreach ($rows as $value) {
90
            $a = $this->readAndInsert($select_column, $table_columns, $value);
91
92
            $has_title_field = true;
93
            foreach ($a as $k => $v) {
94
                if ($k == $titleField && $v == '') {
95
                    $has_title_field = false;
96
                    break;
97
                }
98
            }
99
100
            if ($has_title_field == false) {
101
                continue;
102
            }
103
104
            try {
105
                if (\Schema::hasColumn($table, 'created_at')) {
106
                    $a['created_at'] = date('Y-m-d H:i:s');
107
                }
108
109
                \DB::table($table)->insert($a);
110
                Cache::increment('success_'.$file_md5);
111
            } catch (\Exception $e) {
112
                $e = (string) $e;
113
                Cache::put('error_'.$file_md5, $e, 500);
114
            }
115
        }
116
    }
117
118
    /**
119
     * @param $select_column
120
     * @param $table_columns
121
     * @param $value
122
     * @return array
123
     */
124
    private function readAndInsert($select_column, $table_columns, $value)
125
    {
126
        $a = [];
127
        foreach ($select_column as $sk => $s) {
128
            $colname = $table_columns[$sk];
129
130
            if (! CRUDBooster::isForeignKey($colname) || intval($value->$s)) {
131
                $a[$colname] = $value->$s;
132
                continue;
133
            }
134
135
            //Skip if value is empty
136
            if ($value->$s == '') {
137
                continue;
138
            }
139
140
            $relation_table = CRUDBooster::getTableForeignKey($colname);
141
            $relation_moduls = DB::table('cms_moduls')->where('table_name', $relation_table)->first();
142
143
            $relation_class = __NAMESPACE__.'\\'.$relation_moduls->controller;
144
            if (! class_exists($relation_class)) {
145
                $relation_class = '\App\Http\Controllers\\'.$relation_moduls->controller;
146
            }
147
            $relation_class = new $relation_class;
148
            $relation_class->genericLoader();
149
150
            $title_field = $relation_class->title_field;
151
152
            $relation_insert_data = [];
153
            $relation_insert_data[$title_field] = $value->$s;
154
155
            if (\Schema::hasColumn($relation_table, 'created_at')) {
156
                $relation_insert_data['created_at'] = date('Y-m-d H:i:s');
157
            }
158
159
            try {
160
                $relation_exists = DB::table($relation_table)->where($title_field, $value->$s)->first();
161
                if ($relation_exists) {
162
                    $relation_primary_key = $relation_class->primary_key;
163
                    $relation_id = $relation_exists->$relation_primary_key;
164
                } else {
165
                    $relation_id = DB::table($relation_table)->insertGetId($relation_insert_data);
166
                }
167
168
                $a[$colname] = $relation_id;
169
            } catch (\Exception $e) {
170
                exit($e);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
171
            }
172
        }
173
174
        return $a;
175
    }
176
}