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