Conditions | 9 |
Paths | 16 |
Total Lines | 58 |
Code Lines | 31 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
109 | public function apiSaveForm(HTTPRequest $request) |
||
110 | { |
||
111 | // Validate required input data |
||
112 | if (!isset($this->urlParams['ID'])) { |
||
113 | $this->jsonError(400); |
||
114 | return null; |
||
115 | } |
||
116 | |||
117 | $data = Convert::json2array($request->getBody()); |
||
118 | if (empty($data)) { |
||
119 | $this->jsonError(400); |
||
120 | return null; |
||
121 | } |
||
122 | |||
123 | // Inject request body as request vars |
||
124 | foreach ($data as $key => $value) { |
||
125 | $request->offsetSet($key, $value); |
||
126 | } |
||
127 | |||
128 | // Check security token |
||
129 | if (!SecurityToken::inst()->checkRequest($request)) { |
||
130 | $this->jsonError(400); |
||
131 | return null; |
||
132 | } |
||
133 | |||
134 | /** @var BaseElement $element */ |
||
135 | $element = BaseElement::get()->byID($this->urlParams['ID']); |
||
136 | // Ensure the element can be edited by the current user |
||
137 | if (!$element || !$element->canEdit()) { |
||
138 | $this->jsonError(403); |
||
139 | return null; |
||
140 | } |
||
141 | |||
142 | // Remove the pseudo namespaces that were added by the form factory |
||
143 | $data = $this->removeNamespacesFromFields($data, $element->ID); |
||
144 | |||
145 | try { |
||
146 | $updated = false; |
||
147 | |||
148 | $element->updateFromFormData($data); |
||
149 | // Check if anything will actually be changed before writing |
||
150 | if ($element->isChanged()) { |
||
151 | $element->write(); |
||
152 | // Track changes so we can return to the client |
||
153 | $updated = true; |
||
154 | } |
||
155 | } catch (Exception $ex) { |
||
156 | Injector::inst()->get(LoggerInterface::class)->debug($ex->getMessage()); |
||
157 | |||
158 | $this->jsonError(500); |
||
159 | return null; |
||
160 | } |
||
161 | |||
162 | $body = Convert::raw2json([ |
||
163 | 'status' => 'success', |
||
164 | 'updated' => $updated, |
||
165 | ]); |
||
166 | return HTTPResponse::create($body)->addHeader('Content-Type', 'application/json'); |
||
167 | } |
||
213 |