Conditions | 5 |
Paths | 24 |
Total Lines | 51 |
Code Lines | 27 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
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 |
||
37 | public function add( |
||
38 | Request $request, |
||
39 | ORMInterface $orm, |
||
40 | ResponseFactoryInterface $responseFactory, |
||
41 | UrlGeneratorInterface $urlGenerator, |
||
42 | UserComponent $userComponent |
||
43 | ): Response |
||
44 | { |
||
45 | $body = $request->getParsedBody(); |
||
46 | $parameters = [ |
||
47 | 'body' => $body, |
||
48 | ]; |
||
49 | |||
50 | if ($request->getMethod() === Method::POST) { |
||
51 | $error = ''; |
||
|
|||
52 | |||
53 | try { |
||
54 | foreach (['header', 'content'] as $name) { |
||
55 | if (empty($body[$name])) { |
||
56 | throw new \InvalidArgumentException(ucfirst($name) . ' is required'); |
||
57 | } |
||
58 | } |
||
59 | |||
60 | $post = new Post($body['header'], $body['content']); |
||
61 | |||
62 | $userRepo = $orm->getRepository(User::class); |
||
63 | $user = $userRepo->findByPK($userComponent->getId()); |
||
64 | |||
65 | $post->setUser($user); |
||
66 | $post->setPublic(true); |
||
67 | |||
68 | $transaction = new Transaction($orm); |
||
69 | $transaction->persist($post); |
||
70 | |||
71 | $transaction->run(); |
||
72 | |||
73 | return $responseFactory |
||
74 | ->createResponse(302) |
||
75 | ->withHeader( |
||
76 | 'Location', |
||
77 | $urlGenerator->generate('blog/index') |
||
78 | ); |
||
79 | } catch (\Throwable $e) { |
||
80 | $error = $e->getMessage(); |
||
81 | } |
||
82 | |||
83 | $parameters['error'] = $error; |
||
84 | } |
||
85 | |||
86 | $parameters['title'] = 'Add post'; |
||
87 | return $this->viewRenderer->withCsrf()->render('__form', $parameters); |
||
88 | } |
||
147 |