Passed
Push — master ( 8e610a...5c833b )
by Alexander
13:18
created

PostController::add()   B

Complexity

Conditions 6
Paths 25

Size

Total Lines 54
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 31
nc 25
nop 3
dl 0
loc 54
rs 8.8017
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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:

1
<?php
2
3
namespace App\Blog\Post;
4
5
use App\Blog\Entity\Post;
6
use App\Entity\User;
7
use App\ViewRenderer;
8
use Cycle\ORM\ORMInterface;
9
use Cycle\ORM\Transaction;
10
use Psr\Http\Message\ResponseFactoryInterface;
11
use Psr\Http\Message\ResponseInterface as Response;
12
use Psr\Http\Message\ServerRequestInterface as Request;
13
use Psr\Log\LoggerInterface;
14
use Yiisoft\Access\AccessCheckerInterface;
15
use Yiisoft\Http\Method;
16
use Yiisoft\Router\UrlGeneratorInterface;
17
use Yiisoft\Yii\Web\User\User as UserComponent;
18
19
final class PostController
20
{
21
    private ViewRenderer $viewRenderer;
22
    private ResponseFactoryInterface $responseFactory;
23
    private LoggerInterface $logger;
24
    private UserComponent $userService;
25
26
    public function __construct(
27
        ViewRenderer $viewRenderer,
28
        ResponseFactoryInterface $responseFactory,
29
        LoggerInterface $logger,
30
        UserComponent $userService
31
    ) {
32
        $this->viewRenderer = $viewRenderer->withControllerName('blog/post');
33
        $this->responseFactory = $responseFactory;
34
        $this->logger = $logger;
35
        $this->userService = $userService;
36
    }
37
38
    public function index(Request $request, PostRepository $postRepository, AccessCheckerInterface $accessChecker): Response
39
    {
40
        $userId = $this->userService->getId();
41
        $canEdit = !is_null($userId) && $accessChecker->userHasPermission($userId, 'editPost');
42
43
        $slug = $request->getAttribute('slug', null);
44
        $item = $postRepository->fullPostPage($slug);
45
        if ($item === null) {
46
            return $this->responseFactory->createResponse(404);
47
        }
48
49
        return $this->viewRenderer->render('index', ['item' => $item, 'canEdit' => $canEdit, 'slug' => $slug]);
50
    }
51
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 = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $error is dead and can be removed.
Loading history...
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);
0 ignored issues
show
Bug introduced by
It seems like $user can also be of type null; however, parameter $user of App\Blog\Entity\Post::setUser() does only seem to accept App\Entity\User, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

82
                $post->setUser(/** @scrutinizer ignore-type */ $user);
Loading history...
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
    }
107
108
    public function edit(
109
        Request $request,
110
        ORMInterface $orm,
111
        UrlGeneratorInterface $urlGenerator,
112
        PostRepository $postRepository,
113
        AccessCheckerInterface $accessChecker
114
    ): Response {
115
        $userId = $this->userService->getId();
116
        if (is_null($userId) || !$accessChecker->userHasPermission($userId, 'editPost')) {
117
            return $this->responseFactory->createResponse(403);
118
        }
119
120
        $slug = $request->getAttribute('slug', null);
121
        $post = $postRepository->fullPostPage($slug);
122
        if ($post === null) {
123
            return $this->responseFactory->createResponse(404);
124
        }
125
126
        $parameters = [];
127
        $parameters['action'] = ['blog/edit', ['slug' => $slug]];
128
129
        if ($request->getMethod() === Method::POST) {
130
            $error = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $error is dead and can be removed.
Loading history...
131
132
            try {
133
                $body = $request->getParsedBody();
134
                $parameters['body'] = $body;
135
136
                foreach (['title', 'content'] as $name) {
137
                    if (empty($body[$name])) {
138
                        throw new \InvalidArgumentException(ucfirst($name) . ' is required');
139
                    }
140
                }
141
142
                $post->setTitle($body['title']);
143
                $post->setContent($body['content']);
144
145
                $transaction = new Transaction($orm);
146
                $transaction->persist($post);
147
148
                $transaction->run();
149
150
                return $this->responseFactory
151
                    ->createResponse(302)
152
                    ->withHeader(
153
                        'Location',
154
                        $urlGenerator->generate('blog/index')
155
                    );
156
            } catch (\Throwable $e) {
157
                $this->logger->error($e);
158
                $error = $e->getMessage();
159
            }
160
161
            $parameters['error'] = $error;
162
        } else {
163
            $parameters['body'] = [
164
                'title' => $post->getTitle(),
165
                'content' => $post->getContent(),
166
            ];
167
        }
168
169
        $parameters['title'] = 'Edit post';
170
        return $this->viewRenderer->withCsrf()->render('__form', $parameters);
171
    }
172
}
173