Completed
Pull Request — master (#16)
by Simon
06:16
created

PartialSubmissionController   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 97.14%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 12
dl 0
loc 176
ccs 68
cts 70
cp 0.9714
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B savePartialSubmission() 0 49 8
A createOrUpdateSubmission() 0 18 3
A savePartialField() 0 17 4
A savePartialFile() 0 20 5
A uploadFile() 0 16 3
1
<?php
2
3
namespace Firesphere\PartialUserforms\Controllers;
4
5
use Exception;
6
use Firesphere\PartialUserforms\Models\PartialFieldSubmission;
7
use Firesphere\PartialUserforms\Models\PartialFileFieldSubmission;
8
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
9
use SilverStripe\Assets\File;
10
use SilverStripe\Assets\Upload;
11
use SilverStripe\CMS\Controllers\ContentController;
12
use SilverStripe\Control\HTTPRequest;
13
use SilverStripe\Control\HTTPResponse;
14
use SilverStripe\ORM\DataObject;
15
use SilverStripe\ORM\ValidationException;
16
use SilverStripe\UserForms\Model\EditableFormField;
17
18
/**
19
 * Class PartialSubmissionController
20
 *
21
 * @package Firesphere\PartialUserforms\Controllers
22
 */
23
class PartialSubmissionController extends ContentController
24
{
25
    /**
26
     * Session key name
27
     */
28
    public const SESSION_KEY = 'PartialSubmissionID';
29
30
    /**
31
     * @var array
32
     */
33
    private static $url_handlers = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
34
        'save' => 'savePartialSubmission',
35
    ];
36
37
    /**
38
     * @var array
39
     */
40
    private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
41
        'savePartialSubmission',
42
    ];
43
44
    /**
45
     * @param HTTPRequest $request
46
     * @return HTTPResponse
47
     * @throws ValidationException
48
     * @throws \SilverStripe\Control\HTTPResponse_Exception
49
     */
50 9
    public function savePartialSubmission(HTTPRequest $request)
51
    {
52 9
        if (!$request->isPOST()) {
53
            return $this->httpError(404);
54
        }
55
56 9
        $postVars = $request->postVars();
57 9
        $editableField = null;
58
59
        // We don't want SecurityID and/or the process Action stored as a thing
60 9
        unset($postVars['SecurityID'], $postVars['action_process']);
61 9
        $submissionID = $request->getSession()->get(self::SESSION_KEY);
62
63
        /** @var PartialFormSubmission $partialSubmission */
64 9
        $partialSubmission = PartialFormSubmission::get()->byID($submissionID);
65
66 9
        if (!$submissionID || !$partialSubmission) {
67 9
            $partialSubmission = PartialFormSubmission::create();
68
            // TODO: Set the Parent ID and Parent Class before write, this issue will create new submissions
69
            // every time the session expires when the user proceeds to the next step.
70
            // Also, saving a new submission without a parent creates an
71
            // "AccordionItems" as parent class (first DataObject found)
72 9
            $submissionID = $partialSubmission->write();
73
        }
74 9
        $request->getSession()->set(self::SESSION_KEY, $submissionID);
75 9
        foreach ($postVars as $field => $value) {
76
            /** @var EditableFormField $editableField */
77 9
            $editableField = $this->createOrUpdateSubmission([
78 9
                'Name'            => $field,
79 9
                'Value'           => $value,
80 9
                'SubmittedFormID' => $submissionID
81
            ]);
82
        }
83
84 9
        if ($editableField instanceof EditableFormField && !$partialSubmission->UserDefinedFormID) {
85
            // Updates parent class to the correct DataObject
86 9
            $partialSubmission->update([
87 9
                'UserDefinedFormID'    => $editableField->Parent()->ID,
88 9
                'ParentID'             => $editableField->Parent()->ID,
89 9
                'ParentClass'          => $editableField->Parent()->ClassName,
90 9
                'UserDefinedFormClass' => $editableField->Parent()->ClassName
91
            ]);
92 9
            $partialSubmission->write();
93
        }
94
95 9
        $return = $partialSubmission->exists();
96
97 9
        return new HTTPResponse($return, ($return ? 201 : 400));
0 ignored issues
show
Documentation introduced by
$return is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
98
    }
99
100
    /**
101
     * @param $formData
102
     * @return DataObject|EditableFormField
103
     * @throws ValidationException
104
     */
105 9
    protected function createOrUpdateSubmission($formData)
106
    {
107
        $filter = [
108 9
            'Name'            => $formData['Name'],
109 9
            'SubmittedFormID' => $formData['SubmittedFormID'],
110
        ];
111
112
        /** @var EditableFormField $editableField */
113 9
        $editableField = EditableFormField::get()->filter(['Name' => $formData['Name']])->first();
114 9
        if ($editableField instanceof EditableFormField\EditableFileField) {
115 1
            $this->savePartialFile($formData, $filter, $editableField);
116 8
        } elseif ($editableField instanceof EditableFormField) {
117 8
            $this->savePartialField($formData, $filter, $editableField);
118
        }
119
120
        // Return the ParentID to link the PartialSubmission to it's proper thingy
121 9
        return $editableField;
122
    }
123
124
    /**
125
     * @param $formData
126
     * @param array $filter
127
     * @param EditableFormField $editableField
128
     * @throws ValidationException
129
     */
130 8
    protected function savePartialField($formData, array $filter, EditableFormField $editableField)
131
    {
132 8
        $partialSubmission = PartialFieldSubmission::get()->filter($filter)->first();
133 8
        if (is_array($formData['Value'])) {
134 1
            $formData['Value'] = implode(', ', $formData['Value']);
135
        }
136 8
        if ($editableField) {
137 8
            $formData['Title'] = $editableField->Title;
138 8
            $formData['ParentClass'] = $editableField->Parent()->ClassName;
139
        }
140 8
        if (!$partialSubmission) {
141 8
            $partialSubmission = PartialFieldSubmission::create($formData);
142
        } else {
143 2
            $partialSubmission->update($formData);
144
        }
145 8
        $partialSubmission->write();
146 8
    }
147
148
    /**
149
     * @param $formData
150
     * @param array $filter
151
     * @param EditableFormField\EditableFileField $editableField
152
     * @throws ValidationException
153
     * @throws Exception
154
     */
155 1
    protected function savePartialFile($formData, array $filter, EditableFormField\EditableFileField $editableField)
156
    {
157 1
        $partialFileSubmission = PartialFileFieldSubmission::get()->filter($filter)->first();
158 1
        if (!$partialFileSubmission && $editableField) {
159
            $partialData = [
160 1
                'Name'            => $formData['Name'],
161 1
                'SubmittedFormID' => $formData['SubmittedFormID'],
162 1
                'Title'           => $editableField->Title,
163 1
                'ParentClass'     => $editableField->Parent()->ClassName
164
            ];
165 1
            $partialFileSubmission = PartialFileFieldSubmission::create($partialData);
166 1
            $partialFileSubmission->write();
167
        }
168
        // Don't overwrite existing uploads
169 1
        if (!$partialFileSubmission->UploadedFileID && is_array($formData['Value'])) {
170 1
            $file = $this->uploadFile($formData, $editableField);
171 1
            $partialFileSubmission->UploadedFileID = $file->ID ?? 0;
172
        }
173 1
        $partialFileSubmission->write();
174 1
    }
175
176
    /**
177
     * @param array $formData
178
     * @param EditableFormField\EditableFileField $field
179
     * @return bool|File
180
     * @throws \Exception
181
     */
182 1
    protected function uploadFile($formData, $field)
183
    {
184 1
        if (!empty($formData['Value']['name'])) {
185 1
            $foldername = $field->getFormField()->getFolderName();
186
187
            // create the file from post data
188 1
            $upload = Upload::create();
189 1
            $file = File::create();
190 1
            $file->ShowInSearch = 0;
191 1
            if ($upload->loadIntoFile($formData['Value'], $file, $foldername)) {
192 1
                return $file;
193
            }
194
        }
195
196
        return false;
197
    }
198
}
199