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