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