Passed
Push — master ( cf712f...c12d7d )
by Luiz Kim
08:30
created

CreateUserAction::deleteUser()   A

Complexity

Conditions 6
Paths 25

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 32
rs 9.0111
cc 6
nc 25
nop 2
1
<?php
2
3
namespace ControleOnline\Controller;
4
5
use Symfony\Component\HttpFoundation\Request;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Doctrine\ORM\EntityManagerInterface;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Symfony\Component\HttpFoundation\JsonResponse;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\JsonResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Symfony\Component\Security\Core\Security;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Security\Core\Security was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Securi...asswordEncoderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
11
use ControleOnline\Entity\People;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\People was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use ControleOnline\Entity\User;
13
use ControleOnline\Entity\Person;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Person was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
15
class CreateUserAction
16
{
17
    /**
18
     * Entity Manager
19
     *
20
     * @var EntityManagerInterface
21
     */
22
    private $manager = null;
23
24
    /**
25
     * Request
26
     *
27
     * @var Request
28
     */
29
    private $request  = null;
30
31
    /**
32
     * Security
33
     *
34
     * @var Security
35
     */
36
    private $security = null;
37
38
    /**
39
     * Current user
40
     *
41
     * @var \ControleOnline\Entity\User
42
     */
43
    private $currentUser = null;
44
45
    /**
46
     * Password encoder
47
     *
48
     * @var UserPasswordEncoderInterface
49
     */
50
    private $encoder = null;
51
52
    public function __construct(EntityManagerInterface $manager, Security $security, UserPasswordEncoderInterface $passwordEncoder)
53
    {
54
        $this->manager     = $manager;
55
        $this->security    = $security;
56
        $this->currentUser = $security->getUser();
57
        $this->encoder     = $passwordEncoder;
58
    }
59
60
    public function __invoke(Person $data, Request $request): JsonResponse
61
    {
62
        $this->request = $request;
63
64
        try {
65
            $payload   = json_decode($this->request->getContent(), true);
66
            $result    = $this->addUser($data, $payload);
67
68
            return new JsonResponse([
69
                'response' => [
70
                    'data'    => $result,
71
                    'count'   => 1,
72
                    'error'   => '',
73
                    'success' => true,
74
                ],
75
            ], 200);
76
77
        } catch (\Exception $e) {
78
79
            return new JsonResponse([
80
                'response' => [
81
                    'data'    => [],
82
                    'count'   => 0,
83
                    'error'   => $e->getMessage(),
84
                    'success' => false,
85
                ],
86
            ]);
87
88
        }
89
    }
90
91
    private function addUser(Person $person, array $payload): ?array
92
    {
93
        try {
94
            $this->manager->getConnection()->beginTransaction();
95
96
            if (!isset($payload['username']) || empty($payload['username'])) {
97
                throw new \InvalidArgumentException('Username param is not valid');
98
            }
99
100
            if (!isset($payload['password']) || empty($payload['password'])) {
101
                throw new \InvalidArgumentException('Password param is not valid');
102
            }
103
104
            $company = $this->manager->getRepository(People::class)->find($person->getId());
105
            $user    = $this->manager->getRepository(User::class)->findOneBy(['username' => $payload['username']]);
106
            if ($user instanceof User) {
107
                throw new \InvalidArgumentException('O username já esta em uso');
108
            }
109
110
            $user = new User();
111
            $user->setUsername($payload['username']);
112
            $user->setHash    ($this->encoder->encodePassword($user, $payload['password']));
113
            $user->setPeople  ($company);
114
115
            $this->manager->persist($user);
116
117
            $this->manager->flush();
118
            $this->manager->getConnection()->commit();
119
120
            return [
121
                'id' => $user->getId()
122
            ];
123
124
        } catch (\Exception $e) {
125
            if ($this->manager->getConnection()->isTransactionActive())
126
                $this->manager->getConnection()->rollBack();
127
128
            throw new \InvalidArgumentException($e->getMessage());
129
        }
130
    }
131
132
    private function deleteUser(Person $person, array $payload): bool
0 ignored issues
show
Unused Code introduced by
The method deleteUser() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
133
    {
134
        try {
135
            $this->manager->getConnection()->beginTransaction();
136
137
            if (!isset($payload['id'])) {
138
                throw new \InvalidArgumentException('Document id is not defined');
139
            }
140
141
            $company = $this->manager->getRepository(People::class)->find($person->getId());
142
            $users   = $this->manager->getRepository(User::class)->findBy(['people' => $company]);
143
            if (count($users) == 1) {
144
                throw new \InvalidArgumentException('Deve existir pelo menos um usuário');
145
            }
146
147
            $user    = $this->manager->getRepository(User::class)->findOneBy(['id' => $payload['id'], 'people' => $company]);
148
            if (!$user instanceof User) {
149
                throw new \InvalidArgumentException('Person user was not found');
150
            }
151
152
            $this->manager->remove($user);
153
154
            $this->manager->flush();
155
            $this->manager->getConnection()->commit();
156
157
            return true;
158
159
        } catch (\Exception $e) {
160
            if ($this->manager->getConnection()->isTransactionActive())
161
                $this->manager->getConnection()->rollBack();
162
163
            throw new \InvalidArgumentException($e->getMessage());
164
        }
165
    }
166
167
    private function getUsers(Person $person, ?array $payload = null): array
0 ignored issues
show
Unused Code introduced by
The parameter $payload is not used and could be removed. ( Ignorable by Annotation )

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

167
    private function getUsers(Person $person, /** @scrutinizer ignore-unused */ ?array $payload = null): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The method getUsers() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
168
    {
169
        $members = [];
170
        $company = $this->manager->getRepository(People::class )->find($person->getId());
171
        $users   = $this->manager->getRepository(User::class)->findBy(['people' => $company]);
172
173
        foreach ($users as $user) {
174
            $members[] = [
175
                'id'       => $user->getId(),
176
                'username' => $user->getUsername(),
177
                'apiKey'   => $user->getApiKey(),
178
            ];
179
        }
180
181
        return [
182
            'members' => $members,
183
            'total'   => count($members),
184
        ];
185
    }
186
}
187