PartialSubmissionController   A
last analyzed

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\Control\HTTPResponse_Exception;
15
use SilverStripe\ORM\DataObject;
16
use SilverStripe\ORM\ValidationException;
17
use SilverStripe\UserForms\Model\EditableFormField;
18
19
/**
20
 * Class PartialSubmissionController
21
 *
22
 * @package Firesphere\PartialUserforms\Controllers
23
 */
24
class PartialSubmissionController extends ContentController
25
{
26
    /**
27
     * Session key name
28
     */
29
    public const SESSION_KEY = 'PartialSubmissionID';
30
31
    /**
32
     * @var array
33
     */
34
    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...
35
        'save' => 'savePartialSubmission',
36
    ];
37
38
    /**
39
     * @var array
40
     */
41
    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...
42
        'savePartialSubmission',
43
    ];
44
45
    /**
46
     * @param HTTPRequest $request
47
     * @return HTTPResponse
48
     * @throws ValidationException
49
     * @throws HTTPResponse_Exception
50
     */
51 9
    public function savePartialSubmission(HTTPRequest $request)
52
    {
53 9
        if (!$request->isPOST()) {
54
            return $this->httpError(404);
55
        }
56
57 9
        $postVars = $request->postVars();
58 9
        $editableField = null;
59
60
        // We don't want SecurityID and/or the process Action stored as a thing
61 9
        unset($postVars['SecurityID'], $postVars['action_process']);
62 9
        $submissionID = $request->getSession()->get(self::SESSION_KEY);
63
64
        /** @var PartialFormSubmission $partialSubmission */
65 9
        $partialSubmission = PartialFormSubmission::get()->byID($submissionID);
66
67 9
        if (!$submissionID || !$partialSubmission) {
68 9
            $partialSubmission = PartialFormSubmission::create();
69
            // TODO: Set the Parent ID and Parent Class before write, this issue will create new submissions
70
            // every time the session expires when the user proceeds to the next step.
71
            // Also, saving a new submission without a parent creates an
72
            // "AccordionItems" as parent class (first DataObject found)
73 9
            $submissionID = $partialSubmission->write();
74
        }
75 9
        $request->getSession()->set(self::SESSION_KEY, $submissionID);
76 9
        foreach ($postVars as $field => $value) {
77
            /** @var EditableFormField $editableField */
78 9
            $editableField = $this->createOrUpdateSubmission([
79 9
                'Name'            => $field,
80 9
                'Value'           => $value,
81 9
                'SubmittedFormID' => $submissionID
82
            ]);
83
        }
84
85 9
        if ($editableField instanceof EditableFormField && !$partialSubmission->UserDefinedFormID) {
86
            // Updates parent class to the correct DataObject
87 9
            $partialSubmission->update([
88 9
                'UserDefinedFormID'    => $editableField->Parent()->ID,
89 9
                'ParentID'             => $editableField->Parent()->ID,
90 9
                'ParentClass'          => $editableField->Parent()->ClassName,
91 9
                'UserDefinedFormClass' => $editableField->Parent()->ClassName
92
            ]);
93 9
            $partialSubmission->write();
94
        }
95
96 9
        $return = $partialSubmission->exists();
97
98 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...
99
    }
100
101
    /**
102
     * @param $formData
103
     * @return DataObject|EditableFormField
104
     * @throws ValidationException
105
     */
106 9
    protected function createOrUpdateSubmission($formData)
107
    {
108
        $filter = [
109 9
            'Name'            => $formData['Name'],
110 9
            'SubmittedFormID' => $formData['SubmittedFormID'],
111
        ];
112
113
        /** @var EditableFormField $editableField */
114 9
        $editableField = EditableFormField::get()->filter(['Name' => $formData['Name']])->first();
115 9
        if ($editableField instanceof EditableFormField\EditableFileField) {
116 1
            $this->savePartialFile($formData, $filter, $editableField);
117 8
        } elseif ($editableField instanceof EditableFormField) {
118 8
            $this->savePartialField($formData, $filter, $editableField);
119
        }
120
121
        // Return the ParentID to link the PartialSubmission to it's proper thingy
122 9
        return $editableField;
123
    }
124
125
    /**
126
     * @param $formData
127
     * @param array $filter
128
     * @param EditableFormField $editableField
129
     * @throws ValidationException
130
     */
131 8
    protected function savePartialField($formData, array $filter, EditableFormField $editableField)
132
    {
133 8
        $partialSubmission = PartialFieldSubmission::get()->filter($filter)->first();
134 8
        if (is_array($formData['Value'])) {
135 1
            $formData['Value'] = implode(', ', $formData['Value']);
136
        }
137 8
        if ($editableField) {
138 8
            $formData['Title'] = $editableField->Title;
139 8
            $formData['ParentClass'] = $editableField->Parent()->ClassName;
140
        }
141 8
        if (!$partialSubmission) {
142 8
            $partialSubmission = PartialFieldSubmission::create($formData);
143
        } else {
144 2
            $partialSubmission->update($formData);
145
        }
146 8
        $partialSubmission->write();
147 8
    }
148
149
    /**
150
     * @param $formData
151
     * @param array $filter
152
     * @param EditableFormField\EditableFileField $editableField
153
     * @throws ValidationException
154
     * @throws Exception
155
     */
156 1
    protected function savePartialFile($formData, array $filter, EditableFormField\EditableFileField $editableField)
157
    {
158 1
        $partialFileSubmission = PartialFileFieldSubmission::get()->filter($filter)->first();
159 1
        if (!$partialFileSubmission && $editableField) {
160
            $partialData = [
161 1
                'Name'            => $formData['Name'],
162 1
                'SubmittedFormID' => $formData['SubmittedFormID'],
163 1
                'Title'           => $editableField->Title,
164 1
                'ParentClass'     => $editableField->Parent()->ClassName
165
            ];
166 1
            $partialFileSubmission = PartialFileFieldSubmission::create($partialData);
167 1
            $partialFileSubmission->write();
168
        }
169
        // Don't overwrite existing uploads
170 1
        if (!$partialFileSubmission->UploadedFileID && is_array($formData['Value'])) {
171 1
            $file = $this->uploadFile($formData, $editableField);
172 1
            $partialFileSubmission->UploadedFileID = $file->ID ?? 0;
173
        }
174 1
        $partialFileSubmission->write();
175 1
    }
176
177
    /**
178
     * @param array $formData
179
     * @param EditableFormField\EditableFileField $field
180
     * @return bool|File
181
     * @throws \Exception
182
     */
183 1
    protected function uploadFile($formData, $field)
184
    {
185 1
        if (!empty($formData['Value']['name'])) {
186 1
            $foldername = $field->getFormField()->getFolderName();
187
188
            // create the file from post data
189 1
            $upload = Upload::create();
190 1
            $file = File::create();
191 1
            $file->ShowInSearch = 0;
192 1
            if ($upload->loadIntoFile($formData['Value'], $file, $foldername)) {
193 1
                return $file;
194
            }
195
        }
196
197
        return false;
198
    }
199
}
200