| Conditions | 9 | 
| Paths | 16 | 
| Total Lines | 57 | 
| 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 | $element->update($data); | ||
| 148 | // Check if anything will actually be changed before writing | ||
| 149 |             if ($element->isChanged()) { | ||
| 150 | $element->write(); | ||
| 151 | // Track changes so we can return to the client | ||
| 152 | $updated = true; | ||
| 153 | } | ||
| 154 |         } catch (Exception $ex) { | ||
| 155 | Injector::inst()->get(LoggerInterface::class)->debug($ex->getMessage()); | ||
| 156 | |||
| 157 | $this->jsonError(500); | ||
| 158 | return null; | ||
| 159 | } | ||
| 160 | |||
| 161 | $body = Convert::raw2json([ | ||
| 162 | 'status' => 'success', | ||
| 163 | 'updated' => $updated, | ||
| 164 | ]); | ||
| 165 |         return HTTPResponse::create($body)->addHeader('Content-Type', 'application/json'); | ||
| 166 | } | ||
| 212 |