| Conditions | 8 |
| Paths | 22 |
| Total Lines | 63 |
| Code Lines | 37 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 3 | ||
| Bugs | 0 | Features | 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 |
||
| 108 | public function edit( |
||
| 109 | Request $request, |
||
| 110 | ORMInterface $orm, |
||
| 111 | UrlGeneratorInterface $urlGenerator, |
||
| 112 | PostRepository $postRepository, |
||
| 113 | AccessCheckerInterface $accessChecker |
||
| 114 | ): Response { |
||
| 115 | $userId = $this->userService->getId(); |
||
| 116 | if (is_null($userId) || !$accessChecker->userHasPermission($userId, 'editPost')) { |
||
| 117 | return $this->responseFactory->createResponse(403); |
||
| 118 | } |
||
| 119 | |||
| 120 | $slug = $request->getAttribute('slug', null); |
||
| 121 | $post = $postRepository->fullPostPage($slug); |
||
| 122 | if ($post === null) { |
||
| 123 | return $this->responseFactory->createResponse(404); |
||
| 124 | } |
||
| 125 | |||
| 126 | $parameters = []; |
||
| 127 | $parameters['action'] = ['blog/edit', ['slug' => $slug]]; |
||
| 128 | |||
| 129 | if ($request->getMethod() === Method::POST) { |
||
| 130 | $error = ''; |
||
| 131 | |||
| 132 | try { |
||
| 133 | $body = $request->getParsedBody(); |
||
| 134 | $parameters['body'] = $body; |
||
| 135 | |||
| 136 | foreach (['title', 'content'] as $name) { |
||
| 137 | if (empty($body[$name])) { |
||
| 138 | throw new \InvalidArgumentException(ucfirst($name) . ' is required'); |
||
| 139 | } |
||
| 140 | } |
||
| 141 | |||
| 142 | $post->setTitle($body['title']); |
||
| 143 | $post->setContent($body['content']); |
||
| 144 | |||
| 145 | $transaction = new Transaction($orm); |
||
| 146 | $transaction->persist($post); |
||
| 147 | |||
| 148 | $transaction->run(); |
||
| 149 | |||
| 150 | return $this->responseFactory |
||
| 151 | ->createResponse(302) |
||
| 152 | ->withHeader( |
||
| 153 | 'Location', |
||
| 154 | $urlGenerator->generate('blog/index') |
||
| 155 | ); |
||
| 156 | } catch (\Throwable $e) { |
||
| 157 | $this->logger->error($e); |
||
| 158 | $error = $e->getMessage(); |
||
| 159 | } |
||
| 160 | |||
| 161 | $parameters['error'] = $error; |
||
| 162 | } else { |
||
| 163 | $parameters['body'] = [ |
||
| 164 | 'title' => $post->getTitle(), |
||
| 165 | 'content' => $post->getContent(), |
||
| 166 | ]; |
||
| 167 | } |
||
| 168 | |||
| 169 | $parameters['title'] = 'Edit post'; |
||
| 170 | return $this->viewRenderer->withCsrf()->render('__form', $parameters); |
||
| 171 | } |
||
| 173 |