| 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 |
||
| 105 | public function apiSaveForm(HTTPRequest $request) |
||
| 106 | { |
||
| 107 | // Validate required input data |
||
| 108 | if (!isset($this->urlParams['ID'])) { |
||
| 109 | $this->jsonError(400); |
||
| 110 | return null; |
||
| 111 | } |
||
| 112 | |||
| 113 | $data = Convert::json2array($request->getBody()); |
||
| 114 | if (empty($data)) { |
||
| 115 | $this->jsonError(400); |
||
| 116 | return null; |
||
| 117 | } |
||
| 118 | |||
| 119 | // Inject request body as request vars |
||
| 120 | foreach ($data as $key => $value) { |
||
| 121 | $request->offsetSet($key, $value); |
||
| 122 | } |
||
| 123 | |||
| 124 | // Check security token |
||
| 125 | if (!SecurityToken::inst()->checkRequest($request)) { |
||
| 126 | $this->jsonError(400); |
||
| 127 | return null; |
||
| 128 | } |
||
| 129 | |||
| 130 | /** @var BaseElement $element */ |
||
| 131 | $element = BaseElement::get()->byID($this->urlParams['ID']); |
||
| 132 | // Ensure the element can be edited by the current user |
||
| 133 | if (!$element || !$element->canEdit()) { |
||
| 134 | $this->jsonError(403); |
||
| 135 | return null; |
||
| 136 | } |
||
| 137 | |||
| 138 | // Remove the pseudo namespaces that were added by the form factory |
||
| 139 | $data = $this->removeNamespacesFromFields($data, $element->ID); |
||
| 140 | |||
| 141 | try { |
||
| 142 | $updated = false; |
||
| 143 | $element->update($data); |
||
| 144 | // Check if anything will actually be changed before writing |
||
| 145 | if ($element->isChanged()) { |
||
| 146 | $element->write(); |
||
| 147 | // Track changes so we can return to the client |
||
| 148 | $updated = true; |
||
| 149 | } |
||
| 150 | } catch (Exception $ex) { |
||
| 151 | Injector::inst()->get(LoggerInterface::class)->debug($ex->getMessage()); |
||
| 152 | |||
| 153 | $this->jsonError(500); |
||
| 154 | return null; |
||
| 155 | } |
||
| 156 | |||
| 157 | $body = Convert::raw2json([ |
||
| 158 | 'status' => 'success', |
||
| 159 | 'updated' => $updated, |
||
| 160 | ]); |
||
| 161 | return HTTPResponse::create($body)->addHeader('Content-Type', 'application/json'); |
||
| 162 | } |
||
| 208 |