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