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

PartialUserFormController::savePartialFile()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.3888
c 0
b 0
f 0
cc 5
nc 6
nop 3
1
<?php
2
3
namespace Firesphere\PartialUserforms\Controllers;
4
5
use Firesphere\PartialUserforms\Models\PartialFieldSubmission;
6
use Firesphere\PartialUserforms\Models\PartialFileFieldSubmission;
7
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
8
use SilverStripe\Assets\File;
9
use SilverStripe\Assets\Upload;
10
use SilverStripe\CMS\Controllers\ContentController;
11
use SilverStripe\Control\Controller;
12
use SilverStripe\Control\HTTPRequest;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\ORM\ValidationException;
15
use SilverStripe\ORM\ValidationResult;
16
use SilverStripe\UserForms\Model\EditableFormField;
17
18
/**
19
 * Class \Firesphere\PartialUserforms\Controllers\PartialUserFormController
20
 *
21
 */
22
class PartialUserFormController extends ContentController
23
{
24
    /**
25
     * Session key name
26
     */
27
    const SESSION_KEY = 'PartialSubmissionID';
28
29
    /**
30
     * @var array
31
     */
32
    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...
33
        '' => 'savePartialSubmission'
34
    ];
35
36
    /**
37
     * @var array
38
     */
39
    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...
40
        'savePartialSubmission'
41
    ];
42
43
    /**
44
     * @param HTTPRequest $request
45
     * @return int
46
     * @throws ValidationException
47
     */
48
    public function savePartialSubmission(HTTPRequest $request)
49
    {
50
        $postVars = $request->postVars();
51
        $editableField = null;
52
53
        // We don't want SecurityID and/or the process Action stored as a thing
54
        unset($postVars['SecurityID'], $postVars['action_process']);
55
        $submissionID = $request->getSession()->get(self::SESSION_KEY);
56
57
        /** @var PartialFormSubmission $partialSubmission */
58
        $partialSubmission = PartialFormSubmission::get()->byID($submissionID);
59
60
        if (!$submissionID || !$partialSubmission) {
61
            $partialSubmission = PartialFormSubmission::create();
62
            $submissionID = $partialSubmission->write();
63
        }
64
        $request->getSession()->set(self::SESSION_KEY, $submissionID);
65
        foreach ($postVars as $field => $value) {
66
            /** @var EditableFormField $editableField */
67
            $editableField = $this->createOrUpdateSubmission([
68
                'Name'            => $field,
69
                'Value'           => $value,
70
                'SubmittedFormID' => $submissionID
71
            ]);
72
        }
73
74
        if ($editableField instanceof EditableFormField && !$partialSubmission->UserDefinedFormID) {
75
            $partialSubmission->update([
76
                'UserDefinedFormID'    => $editableField->Parent()->ID,
77
                'ParentID'             => $editableField->Parent()->ID,
78
                'ParentClass'          => $editableField->Parent()->ClassName,
79
                'UserDefinedFormClass' => $editableField->Parent()->ClassName
80
            ]);
81
            $partialSubmission->write();
82
        }
83
84
        return $submissionID;
85
    }
86
87
    /**
88
     * @param $formData
89
     * @return DataObject|EditableFormField
90
     * @throws ValidationException
91
     */
92
    protected function createOrUpdateSubmission($formData)
93
    {
94
        $filter = [
95
            'Name'            => $formData['Name'],
96
            'SubmittedFormID' => $formData['SubmittedFormID'],
97
        ];
98
99
        // Set the title
100
        /** @var EditableFormField $editableField */
101
        $editableField = EditableFormField::get()->filter(['Name' => $formData['Name']])->first();
102
        if ($editableField instanceof EditableFormField\EditableFileField) {
103
            $this->savePartialFile($formData, $filter, $editableField);
104
        } elseif ($editableField instanceof EditableFormField) {
105
            $this->savePartialField($formData, $filter, $editableField);
106
        }
107
108
        // Return the ParentID to link the PartialSubmission to it's proper thingy
109
        return $editableField;
110
    }
111
112
    /**
113
     * @param $formData
114
     * @param array $filter
115
     * @param EditableFormField\EditableFileField $editableField
116
     * @throws ValidationException
117
     * @throws \Exception
118
     */
119
    protected function savePartialFile($formData, array $filter, EditableFormField\EditableFileField $editableField)
120
    {
121
        $partialFileSubmission = PartialFileFieldSubmission::get()->filter($filter)->first();
122
        // Don't overwrite existing uploads
123
        if (!$partialFileSubmission) {
124
            if ($editableField) {
125
                $partialData['Title'] = $editableField->Title;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$partialData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $partialData = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
126
                $partialData['ParentClass'] = $editableField->Parent()->ClassName;
127
            }
128
        }
129
        if (is_array($formData['Value']) && !$partialFileSubmission->UploadedFileID) {
130
            $file = $this->uploadFile($partialData, $editableField);
0 ignored issues
show
Bug introduced by
The variable $partialData does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
131
            $formData['UploadedFileID'] = $file->ID;
132
            $partialFileSubmission = PartialFileFieldSubmission::create($partialData);
133
        }
134
        $partialFileSubmission->write();
135
    }
136
137
    /**
138
     * @param $formData
139
     * @param array $filter
140
     * @param EditableFormField $editableField
141
     * @throws ValidationException
142
     */
143
    protected function savePartialField($formData, array $filter, EditableFormField $editableField): void
144
    {
145
        $exists = PartialFieldSubmission::get()->filter($filter)->first();
146
        if (is_array($formData['Value'])) {
147
            $formData['Value'] = implode(', ', $formData['Value']);
148
        }
149
        if ($editableField) {
150
            $formData['Title'] = $editableField->Title;
151
            $formData['ParentClass'] = $editableField->Parent()->ClassName;
152
        }
153
        if (!$exists) {
154
            $exists = PartialFieldSubmission::create($formData);
155
        } else {
156
            $exists->update($formData);
157
        }
158
        $exists->write();
159
    }
160
161
    /**
162
     * @param array $formData
163
     * @param EditableFormField\EditableFileField $field
164
     * @return File|void
165
     * @throws \Exception
166
     */
167
    protected function uploadFile($formData, $field)
0 ignored issues
show
Unused Code introduced by
The parameter $formData is not used and could be removed.

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

Loading history...
168
    {
169
        if (!empty($_FILES[$field->Name]['name'])) {
170
            $foldername = $field->getFormField()->getFolderName();
171
172
            // create the file from post data
173
            $upload = Upload::create();
174
            $file = File::create();
175
            $file->ShowInSearch = 0;
176
            try {
177
                $upload->loadIntoFile($_FILES[$field->Name], $file, $foldername);
178
            } catch (ValidationException $e) {
179
                $validationResult = $e->getResult();
180
                foreach ($validationResult->getMessages() as $message) {
181
                    $field->Parent()->sessionMessage($message['message'], ValidationResult::TYPE_ERROR);
182
                }
183
                Controller::curr()->redirectBack();
184
                return;
185
            }
186
187
            return $file;
188
        }
189
    }
190
}
191