Conditions | 6 |
Paths | 20 |
Total Lines | 55 |
Code Lines | 31 |
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 |
||
90 | public function edit( |
||
91 | Request $request, |
||
92 | ORMInterface $orm, |
||
93 | ResponseFactoryInterface $responseFactory, |
||
94 | UrlGeneratorInterface $urlGenerator, |
||
95 | PostRepository $postRepository): Response |
||
96 | { |
||
97 | $post = $postRepository->fullPostPage($request->getAttribute('slug', null)); |
||
98 | if ($post === null) { |
||
99 | return $responseFactory->createResponse(404); |
||
100 | } |
||
101 | |||
102 | if ($request->getMethod() === Method::POST) { |
||
103 | try { |
||
104 | $body = $request->getParsedBody(); |
||
105 | $parameters = [ |
||
106 | 'body' => $body, |
||
107 | ]; |
||
108 | |||
109 | foreach (['header', 'content'] as $name) { |
||
110 | if (empty($body[$name])) { |
||
111 | throw new \InvalidArgumentException(ucfirst($name) . ' is required'); |
||
112 | } |
||
113 | } |
||
114 | |||
115 | $post->setTitle($body['header']); |
||
116 | $post->setContent($body['content']); |
||
117 | |||
118 | $transaction = new Transaction($orm); |
||
119 | $transaction->persist($post); |
||
120 | |||
121 | $transaction->run(); |
||
122 | |||
123 | return $responseFactory |
||
124 | ->createResponse(302) |
||
125 | ->withHeader( |
||
126 | 'Location', |
||
127 | $urlGenerator->generate('blog/index') |
||
128 | ); |
||
129 | } catch (\Throwable $e) { |
||
130 | $error = $e->getMessage(); |
||
131 | } |
||
132 | |||
133 | $parameters['error'] = $error; |
||
134 | } else { |
||
135 | $parameters = [ |
||
136 | 'body' => [ |
||
137 | 'header' => $post->getTitle(), |
||
138 | 'content' => $post->getContent() |
||
139 | ] |
||
140 | ]; |
||
141 | } |
||
142 | |||
143 | $parameters['title'] = 'Edit post'; |
||
144 | return $this->viewRenderer->withCsrf()->render('__form', $parameters); |
||
145 | } |
||
147 |