| Conditions | 6 |
| Paths | 25 |
| Total Lines | 54 |
| Code Lines | 31 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 2 | ||
| 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 |
||
| 52 | public function add( |
||
| 53 | Request $request, |
||
| 54 | ORMInterface $orm, |
||
| 55 | UrlGeneratorInterface $urlGenerator |
||
| 56 | ): Response { |
||
| 57 | if ($this->userService->isGuest()) { |
||
| 58 | return $this->responseFactory->createResponse(403); |
||
| 59 | } |
||
| 60 | |||
| 61 | $body = $request->getParsedBody(); |
||
| 62 | $parameters = [ |
||
| 63 | 'body' => $body, |
||
| 64 | 'action' => ['blog/add'] |
||
| 65 | ]; |
||
| 66 | |||
| 67 | if ($request->getMethod() === Method::POST) { |
||
| 68 | $error = ''; |
||
|
|
|||
| 69 | |||
| 70 | try { |
||
| 71 | foreach (['title', 'content'] as $name) { |
||
| 72 | if (empty($body[$name])) { |
||
| 73 | throw new \InvalidArgumentException(ucfirst($name) . ' is required'); |
||
| 74 | } |
||
| 75 | } |
||
| 76 | |||
| 77 | $post = new Post($body['title'], $body['content']); |
||
| 78 | |||
| 79 | $userRepo = $orm->getRepository(User::class); |
||
| 80 | $user = $userRepo->findByPK($this->userService->getId()); |
||
| 81 | |||
| 82 | $post->setUser($user); |
||
| 83 | $post->setPublic(true); |
||
| 84 | |||
| 85 | $transaction = new Transaction($orm); |
||
| 86 | $transaction->persist($post); |
||
| 87 | |||
| 88 | $transaction->run(); |
||
| 89 | |||
| 90 | return $this->responseFactory |
||
| 91 | ->createResponse(302) |
||
| 92 | ->withHeader( |
||
| 93 | 'Location', |
||
| 94 | $urlGenerator->generate('blog/index') |
||
| 95 | ); |
||
| 96 | } catch (\Throwable $e) { |
||
| 97 | $this->logger->error($e); |
||
| 98 | $error = $e->getMessage(); |
||
| 99 | } |
||
| 100 | |||
| 101 | $parameters['error'] = $error; |
||
| 102 | } |
||
| 103 | |||
| 104 | $parameters['title'] = 'Add post'; |
||
| 105 | return $this->viewRenderer->withCsrf()->render('__form', $parameters); |
||
| 106 | } |
||
| 173 |