Test Failed
Branch develop (5056e3)
by Abhishek Kumar
05:17
created

Import::setImportMapRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ladybirdweb\ImportExport;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Storage;
7
use Illuminate\Support\Facades\Validator;
8
use Illuminate\Validation\Rule;
9
use JildertMiedema\LaravelPlupload\Facades\Plupload;
10
use Ladybirdweb\ImportExport\Models\Import as ModelImport;
11
12
class Import
13
{
14
    protected $import_errors = [];
15
16
    protected $upload_route;
17
18
    protected $import_map_route;
19
20
    /**
21
     * Show the form for creating a new import.
22
     *
23
     * @return \Illuminate\Http\Response
24
     */
25
    public function showImportForm()
26
    {
27
        $route = $this->upload_route;
28
29
        return view( 'importexport::import.import', compact( 'route' ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('importexpor...ort', compact('route')) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
30
    }
31
32
33
    /**
34
     * Store a newly created import in storage.
35
     *
36
     * @param  $path
37
     * @param  $columns
38
     * @return integer Import id
39
     */
40
    public function createImport($path, $columns)
41
    {
42
        // Store file path and model class to db
43
        $import = ModelImport::create([
44
            'file' => $path,
45
            'file_rows' => count( file( storage_path( 'app/' . $path ) ) ) - 1,
0 ignored issues
show
Bug introduced by
It seems like file(storage_path('app/' . $path)) can also be of type false; however, parameter $var of count() does only seem to accept Countable|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

45
            'file_rows' => count( /** @scrutinizer ignore-type */ file( storage_path( 'app/' . $path ) ) ) - 1,
Loading history...
46
            'db_cols' => $columns
47
        ]);
48
49
        return $import->id;
50
    }
51
52
53
    /**
54
     * Upload import file in storage.
55
     *
56
     * @param  \Illuminate\Http\Request  $request
57
     * @return \Illuminate\Http\Response
58
     */
59
    public function uploadImportFile(Request $request)
60
    {
61
        // Validate file
62
        $validation = Validator::make($request->all(), [
63
            'file' => 'required|mimes:csv,txt'
64
        ]);
65
66
        if ( $validation->fails() ) {
67
            // Set validator errors
68
            $this->import_errors = $validation->errors();
69
70
            return ['status' => 'failed'];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('status' => 'failed') returns the type array<string,string> which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
71
        }
72
73
        return Plupload::receive('file', function ($file) {
74
75
            // Upload file to storage/app/imports
76
            $path = Storage::putFileAs( 'imports', $file,
77
                'import-' . time() . '.' . $file->getClientOriginalExtension() );           
78
79
            return ['status' => 'ready', 'path' => $path];
80
        });
81
    }
82
83
    /**
84
     * Display the specified resource.
85
     *
86
     * @param  int  $id
87
     * @return \Illuminate\Http\Response
88
     */
89
    public function showImportStatus($id)
90
    {
91
        // Map import instance
92
        $import = ModelImport::findOrFail( $id );
0 ignored issues
show
Unused Code introduced by
The assignment to $import is dead and can be removed.
Loading history...
93
94
        return view( 'importexport::import.progress', compact( 'id' ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('importexpor...ogress', compact('id')) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
95
    }
96
97
    /**
98
     * Show the form for editing the specified resource.
99
     *
100
     * @param  int  $id
101
     * @return \Illuminate\Http\Response
102
     */
103
    public function showColumnsMapForm($id)
104
    {
105
        // Map import instance
106
        $import = ModelImport::findOrFail( $id );
107
        
108
        // Read 5 rows from csv
109
        $read_line = 1;
110
111
        $file = fopen( storage_path( 'app/' . $import->file ), 'r' );
112
113
        while ( $csv_line = fgetcsv( $file ) ) {
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fgetcsv() does only seem to accept resource, 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

113
        while ( $csv_line = fgetcsv( /** @scrutinizer ignore-type */ $file ) ) {
Loading history...
114
            $csv_data[] = $csv_line;
115
116
            if ( $read_line > 5 ) break;
117
118
            $read_line++;
119
        }
120
        
121
        fclose( $file );
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

121
        fclose( /** @scrutinizer ignore-type */ $file );
Loading history...
122
123
        // Get fillable columns
124
        $db_columns = $import->db_cols;
125
126
        // Set post route
127
        $route = $this->import_map_route;
128
129
        return view( 'importexport::import.data_map', compact( 'db_columns', 'csv_data', 'id', 'route' ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('importexpor..._data', 'id', 'route')) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
130
    }
131
132
    /**
133
     * Update the specified resource in storage.
134
     *
135
     * @param  \Illuminate\Http\Request  $request
136
     * @param  int  $id
137
     * @return \Illuminate\Http\Response
138
     */
139
    public function storeColumnsMap(Request $request, $id)
140
    {
141
        // Map import instance
142
        $import = ModelImport::findOrFail( $id );
143
144
        // Get fillable columns
145
        $db_columns = $import->db_cols;
146
147
        // Validate data
148
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Unused Code introduced by
The assignment to $validator is dead and can be removed.
Loading history...
149
            'db_column' => [
150
                'required',
151
                'array',
152
                Rule::in( $db_columns ),
153
                'size:' . count( $db_columns ),
0 ignored issues
show
Bug introduced by
$db_columns of type string is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

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

153
                'size:' . count( /** @scrutinizer ignore-type */ $db_columns ),
Loading history...
154
            ],
155
            'db_column.*' => 'distinct',
156
            'ignore_col' => 'sometimes|array',
157
        ],
158
        [
159
            'required' => implode(', ', $db_columns) . ' are the mandatory columns',
0 ignored issues
show
Bug introduced by
$db_columns of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

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

159
            'required' => implode(', ', /** @scrutinizer ignore-type */ $db_columns) . ' are the mandatory columns',
Loading history...
160
            'in' => implode(', ', $db_columns) . ' are the mandatory columns',
161
            'size' => implode(', ', $db_columns) . ' are the mandatory columns',
162
            'distinct' => 'You can not select one column more than one time',
163
        ])->validate();
164
165
        $db_column = $request->db_column;
166
167
        // Push ignore column to db_column if exists
168
        if ( ! is_null( $request->ignore_col ) ) {
169
            foreach ( $request->ignore_col as $col_no ) {
170
                array_splice( $db_column, $col_no, 0, '');
171
            }
172
        }
173
174
        // Store column map in DB
175
        $import->model_map = $db_column;
176
        $import->save();
177
178
        // Return import instance
179
        return $import;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $import returns the type Ladybirdweb\ImportExport\Models\Import which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
180
    }
181
182
    public function dispatchImportJob( $job, ModelImport $import)
183
    {
184
        // Dispatch import corn job
185
        $job::dispatch( $import )->onQueue( 'importing' );
186
        
187
    }
188
189
    /**
190
     * Remove the specified resource from storage.
191
     *
192
     * @param  int  $id
193
     * @return \Illuminate\Http\Response
194
     */
195
    public function removeImport($id)
196
    {
197
        // Remove a import from db
198
        return ModelImport::findOrFail( $id )->delete();
0 ignored issues
show
Bug Best Practice introduced by
The expression return Ladybirdweb\Impor...ndOrFail($id)->delete() also could return the type boolean which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
199
    }
200
201
    /**
202
     * Return import progress
203
     *
204
     * @param  int  $id
205
     * @return \Illuminate\Http\Response json
206
     */
207
    public function returnImportProgress($id)
208
    {
209
        // Map import instance
210
        $import = ModelImport::findOrFail( $id );
211
212
        $data['status'] = 200;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
213
        $data['progress'] = round( ( $import->row_processed / $import->file_rows ) * 100 );
214
215
        // If progress completed return successful imported rows count
216
        if ( $data['progress'] == 100 ) {
217
            $data['imported'] = $import->row_imported;
218
        }
219
220
        return response()->json( $data );
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json($data) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
221
    }
222
223
    /**
224
     * Get import errors
225
     *
226
     * @return json
0 ignored issues
show
Bug introduced by
The type Ladybirdweb\ImportExport\json 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...
227
     */
228
    public function getImportErrors()
229
    {
230
        return [ 'errors' => $this->import_errors ];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('errors' => $this->import_errors) returns the type array<string,array> which is incompatible with the documented return type Ladybirdweb\ImportExport\json.
Loading history...
231
    }
232
233
    /**
234
     * Set import route
235
     *
236
     * @param  string  $route
237
     */
238
    public function setImportMapRoute($route)
239
    {
240
        $this->import_map_route = $route;
241
    }
242
243
    /**
244
     * Set upload route
245
     *
246
     * @param  string  $route
247
     */
248
    public function setUploadRoute($route)
249
    {
250
        $this->upload_route = $route;
251
    }
252
}
253