Passed
Push — master ( 06f317...3f8050 )
by Luiz Kim
09:56 queued 01:59
created

CreateUserAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 3
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;
12
use ControleOnline\Entity\User;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\User 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...
13
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(People $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
        } catch (\Exception $e) {
77
78
            return new JsonResponse([
79
                'response' => [
80
                    'data'    => [],
81
                    'count'   => 0,
82
                    'error'   => $e->getMessage(),
83
                    'success' => false,
84
                ],
85
            ]);
86
        }
87
    }
88
89
    private function addUser(People $person, array $payload): ?array
90
    {
91
        try {
92
            $this->manager->getConnection()->beginTransaction();
93
94
            if (!isset($payload['username']) || empty($payload['username'])) {
95
                throw new \InvalidArgumentException('Username param is not valid');
96
            }
97
98
            if (!isset($payload['password']) || empty($payload['password'])) {
99
                throw new \InvalidArgumentException('Password param is not valid');
100
            }
101
102
            $company = $this->manager->getRepository(People::class)->find($person->getId());
103
            $user    = $this->manager->getRepository(User::class)->findOneBy(['username' => $payload['username']]);
104
            if ($user instanceof User) {
105
                throw new \InvalidArgumentException('O username já esta em uso');
106
            }
107
108
            $user = new User();
109
            $user->setUsername($payload['username']);
110
            $user->setHash($this->encoder->encodePassword($user, $payload['password']));
111
            $user->setPeople($company);
112
113
            $this->manager->persist($user);
114
115
            $this->manager->flush();
116
            $this->manager->getConnection()->commit();
117
118
            return [
119
                'id' => $user->getId()
120
            ];
121
        } catch (\Exception $e) {
122
            if ($this->manager->getConnection()->isTransactionActive())
123
                $this->manager->getConnection()->rollBack();
124
125
            throw new \InvalidArgumentException($e->getMessage());
126
        }
127
    }
128
    
129
    private function getUsers(People $person, ?array $payload = null): array
0 ignored issues
show
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...
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

129
    private function getUsers(People $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...
130
    {
131
        $members = [];
132
        $company = $this->manager->getRepository(People::class)->find($person->getId());
133
        $users   = $this->manager->getRepository(User::class)->findBy(['people' => $company]);
134
135
        foreach ($users as $user) {
136
            $members[] = [
137
                'id'       => $user->getId(),
138
                'username' => $user->getUsername(),
139
                'apiKey'   => $user->getApiKey(),
140
            ];
141
        }
142
143
        return [
144
            'members' => $members,
145
            'total'   => count($members),
146
        ];
147
    }
148
}
149