SetSpreadsheetStep::fields()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 43
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 43
rs 9.552
c 0
b 0
f 0
cc 3
nc 4
nop 0
1
<?php
2
3
/** Created by PhpStorm,  User: jonphipps,  Date: 2017-05-31,  Time: 11:14 AM */
4
5
namespace App\Wizard\Import\ProjectSteps;
6
7
use App\Models\Batch;
8
use App\Models\Export;
9
use App\Models\Project;
10
use App\Services\Import\GoogleSpreadsheet;
11
use Google_Service_Exception;
12
use Illuminate\Http\Request;
13
use Illuminate\Support\Facades\Validator;
14
use Smajti1\Laravel\Step;
15
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
16
17
class SetSpreadsheetStep extends Step
18
{
19
    public static $label = 'Start with a Spreadsheet URL...';
20
    public static $slug  = 'spreadsheet';
21
    public static $view  = 'frontend.import.project.steps.spreadsheet';
22
    private $sheet;
23
    private $worksheets;
24
    private $title;
25
26
    public function fields(): array
27
    {
28
        $id                = $this->wizard->data()['project_id'];
29
        $batches           = Project::find($id)->importBatches;
30
        $or                = $batches->count() ? 'OR... <br>' : '';
31
        $field_fileName    = [
32
            'name'  => 'source_file_name',
33
            'label' => $or . 'Link to New Google Spreadsheet',
34
            'type'  => 'url',
35
        ];
36
        $field_type        = [
37
            'name'    => 'import_type',
38
            'type'    => 'hidden',
39
            'default' => 0,
40
41
        ];
42
        // $field_type        = [
43
        //     'name'    => 'import_type',
44
        //     'label'   => 'Type of Import',
45
        //     'type'    => 'radio',
46
        //     'options' => [ // the key will be stored in the db, the value will be shown as label;
47
        //                    0 => 'Full -- (Default) Empty cells will be deleted. Empty rows will be deleted, or deprecated if published.',
48
        //                    1 => 'Sparse -- Non-destructive. Empty rows and cells will be ignored.',
49
        //                    2 => 'Partial -- Empty Cells will be deleted. Missing rows will be ignored.',
50
        //     ],
51
        // ];
52
53
        if ($batches->count()) {
54
            $batches           = $batches->pluck('step_data', 'run_description')->mapWithKeys(function ($item, $key) {
55
                return [$item['spreadsheet']['source_file_name'] => $key];
56
            })->sort()->toArray();
57
            $field_sheetSelect = [
58
                'name'        => 'source_file_select',
59
                'label'       => 'Select a previous Google Spreadsheet',
60
                'type'        => 'select2_from_array',
61
                'options'     => $batches,
62
                'allows_null' => true,
63
            ];
64
65
            return [$field_sheetSelect, $field_fileName, $field_type];
66
        }
67
68
        return [$field_fileName, $field_type];
69
    }
70
71
    public function process(Request $request): void
72
    {
73
        //check to see if we have a batch
74
        //if no batch, create one and save the id to the session
75
        // save progress to session
76
        $this->saveProgress($request, ['googlesheets' => $this->worksheets, 'title' => $this->title]);
77
    }
78
79
    public function rules(Request $request = null): array
80
    {
81
        return [
82
            'source_file_name' => 'required|googleUrl',
83
        ];
84
    }
85
86
    /**
87
     * @param Request $request
88
     *
89
     * @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
90
     * @throws \Illuminate\Validation\ValidationException
91
     */
92
    public function validate(Request $request): void
93
    {
94
        $selectedSheet = $request->source_file_select ?? $request->source_file_name;
95
        if ($selectedSheet !== $request->source_file_name) {
96
            $request->merge(['source_file_name' => $request->source_file_select]);
97
        }
98
99
        //here we validate the input from the step
100
        Validator::make($request->all(), $this->rules($request))->validate();
101
        if (! is_readable(base_path('client_secret.json'))) {
102
            throw new InvalidConfigurationException('The Google Spreadsheet Reader Service is not configured correctly');
103
        }
104
        $spread_worksheets = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $spread_worksheets is dead and can be removed.
Loading history...
105
        $spread_sheet      = new GoogleSpreadsheet($selectedSheet);
106
        try {
107
            $spread_worksheets = $spread_sheet->getWorksheets()->toArray();
108
        } catch (Google_Service_Exception $e) {
109
            //we know this is a 403 already, but we're doing this to take advantage of the validate() method's instant redirect
110
            Validator::make(['code' => $e->getCode()],
111
                ['code'        => 'not_in:403'],
112
                ['code.not_in' => 'The import service has not been authorized to read data from this spreadsheet'])
113
                ->validate();
114
        }
115
        $this->sheet = $spread_sheet;
116
        $this->title = $spread_sheet->getSpreadsheetTitle();
117
118
        $worksheets = [];
119
        foreach ($spread_worksheets as $worksheet) {
120
            $sheet = Export::findByExportFileName($worksheet);
121
            if ($sheet) {
122
                $worksheets[$worksheet] = $sheet;
123
            }
124
        }
125
126
        // run the worksheet reader
127
        // compare with known exports and generate a report
128
        Validator::make(['worksheets' => $worksheets],
129
            ['worksheets'          => 'required'],
130
            ['worksheets.required' => 'The supplied spreadsheet has no worksheets that can be matched to an export.'])->validate();
131
132
        $this->worksheets = $worksheets;
133
    }
134
}
135