Completed
Pull Request — master (#13)
by Lhalaa
01:19
created

PartialUserFormController   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 152
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 11
dl 0
loc 152
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B savePartialSubmission() 0 42 7
A createOrUpdateSubmission() 0 29 4
B partial() 0 37 6
1
<?php
2
3
namespace Firesphere\PartialUserforms\Controllers;
4
5
use Firesphere\PartialUserforms\Models\PartialFieldSubmission;
6
use Firesphere\PartialUserforms\Models\PartialFormSubmission;
7
use SilverStripe\CMS\Controllers\ContentController;
8
use SilverStripe\Control\HTTPRequest;
9
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\ValidationException;
12
use SilverStripe\UserForms\Control\UserDefinedFormController;
13
use SilverStripe\UserForms\Model\EditableFormField;
14
use SilverStripe\View\Requirements;
15
16
/**
17
 * Class PartialUserFormController
18
 * @package Firesphere\PartialUserforms\Controllers
19
 */
20
class PartialUserFormController extends ContentController
21
{
22
    /**
23
     * Session key name
24
     */
25
    const SESSION_KEY = 'PartialSubmissionID';
26
27
    /**
28
     * @var array
29
     */
30
    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...
31
        'save' => 'savePartialSubmission',
32
        '$Key/$Token' => 'partial',
33
    ];
34
35
    /**
36
     * @var array
37
     */
38
    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...
39
        'savePartialSubmission',
40
        'partial',
41
    ];
42
43
    /**
44
     * @param HTTPRequest $request
45
     * @return int|mixed|void
46
     * @throws ValidationException
47
     * @throws \SilverStripe\Control\HTTPResponse_Exception
48
     */
49
    public function savePartialSubmission(HTTPRequest $request)
50
    {
51
        if (!$request->isPOST()) {
52
            return $this->httpError(404);
53
        }
54
55
        $postVars = $request->postVars();
56
        $editableField = null;
57
58
        // We don't want SecurityID and/or the process Action stored as a thing
59
        unset($postVars['SecurityID'], $postVars['action_process']);
60
        $submissionID = $request->getSession()->get(self::SESSION_KEY);
61
62
        /** @var PartialFormSubmission $partialSubmission */
63
        $partialSubmission = PartialFormSubmission::get()->byID($submissionID);
64
65
        if (!$submissionID || !$partialSubmission) {
66
            $partialSubmission = PartialFormSubmission::create();
67
            $submissionID = $partialSubmission->write();
68
        }
69
        $request->getSession()->set(self::SESSION_KEY, $submissionID);
70
        foreach ($postVars as $field => $value) {
71
            /** @var EditableFormField $editableField */
72
            $editableField = $this->createOrUpdateSubmission([
73
                'Name'            => $field,
74
                'Value'           => $value,
75
                'SubmittedFormID' => $submissionID
76
            ]);
77
        }
78
79
        if ($editableField instanceof EditableFormField && !$partialSubmission->UserDefinedFormID) {
80
            $partialSubmission->update([
81
                'UserDefinedFormID'    => $editableField->Parent()->ID,
82
                'ParentID'             => $editableField->Parent()->ID,
83
                'ParentClass'          => $editableField->Parent()->ClassName,
84
                'UserDefinedFormClass' => $editableField->Parent()->ClassName
85
            ]);
86
            $partialSubmission->write();
87
        }
88
89
        return $submissionID;
90
    }
91
92
    /**
93
     * @param $formData
94
     * @return DataObject|EditableFormField
95
     * @throws ValidationException
96
     */
97
    protected function createOrUpdateSubmission($formData)
98
    {
99
        if (is_array($formData['Value'])) {
100
            $formData['Value'] = implode(', ', $formData['Value']);
101
        }
102
103
        $filter = [
104
            'Name'            => $formData['Name'],
105
            'SubmittedFormID' => $formData['SubmittedFormID'],
106
        ];
107
108
        $exists = PartialFieldSubmission::get()->filter($filter)->first();
109
        // Set the title
110
        $editableField = EditableFormField::get()->filter(['Name' => $formData['Name']])->first();
111
        if ($editableField) {
112
            $formData['Title'] = $editableField->Title;
113
            $formData['ParentClass'] = $editableField->Parent()->ClassName;
114
        }
115
        if (!$exists) {
116
            $exists = PartialFieldSubmission::create($formData);
117
            $exists->write();
118
        } else {
119
            $exists->update($formData);
120
            $exists->write();
121
        }
122
123
        // Return the ParentID to link the PartialSubmission to it's proper thingy
124
        return $editableField;
125
    }
126
127
    /**
128
     * Partial form
129
     *
130
     * @param HTTPRequest $request
131
     * @return \SilverStripe\ORM\FieldType\DBHTMLText|void
132
     * @throws \SilverStripe\Control\HTTPResponse_Exception
133
     */
134
    public function partial(HTTPRequest $request)
135
    {
136
        $key = $request->param('Key');
137
        $token = $request->param('Token');
138
139
        $partial = PartialFormSubmission::get()->find('Token', $token);
140
        if (!$token || !$partial || !$partial->UserDefinedFormID) {
141
            return $this->httpError(404);
142
        }
143
144
        if ($partial->generateKey($token) === $key) {
145
146
            // Set the session if the last session has expired
147
            if (!$request->getSession()->get(self::SESSION_KEY)) {
148
                $request->getSession()->set(self::SESSION_KEY, $partial->ID);
149
            }
150
151
            // TODO: Recognize visitor with the password
152
            // TODO: Populate form values
153
154
            $record = DataObject::get_by_id($partial->UserDefinedFormClass, $partial->UserDefinedFormID);
155
            $controller = new UserDefinedFormController($record);
156
            $controller->init();
0 ignored issues
show
Bug introduced by
The method init() cannot be called from this context as it is declared protected in class SilverStripe\UserForms\C...erDefinedFormController.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
157
158
            Requirements::javascript('firesphere/partialuserforms:client/dist/main.js');
159
160
            return $this->customise([
161
                'Title' => $record->Title,
162
                'Breadcrumbs' => $record->Breadcrumbs(),
163
                'Content' => $this->obj('Content'),
164
                'Form' => $controller->Form(),
165
                'Link' => $partial->getPartialLink()
166
            ])->renderWith(['PartialUserform', 'Page']);
167
        } else {
168
            return $this->httpError(404);
169
        }
170
    }
171
}
172