Passed
Push — master ( 682802...46670a )
by Maximo
05:00 queued 10s
created

UsersInviteController::insertInvite()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 57
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 8.5213

Importance

Changes 0
Metric Value
cc 7
eloc 34
nc 17
nop 0
dl 0
loc 57
ccs 24
cts 35
cp 0.6857
crap 8.5213
rs 8.4426
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
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\UsersInvite;
8
use Gewaer\Models\Users;
9
use Phalcon\Security\Random;
10
use Phalcon\Validation;
11
use Phalcon\Validation\Validator\PresenceOf;
12
use Phalcon\Validation\Validator\StringLength;
13
use Gewaer\Exception\UnprocessableEntityHttpException;
14
use Gewaer\Exception\NotFoundHttpException;
15
use Gewaer\Exception\ServerErrorHttpException;
16
use Phalcon\Http\Response;
17
use Gewaer\Models\EmailTemplates;
18
19
/**
20
 * Class LanguagesController
21
 * @property Users $userData
22
 * @property Request $request
23
 * @property Config $config
24
 * @property Apps $app
25
 * @property Mail $mail
26
 * @package Gewaer\Api\Controllers
27
 *
28
 */
29
class UsersInviteController extends BaseController
30
{
31
    /*
32
     * fields we accept to create
33
     *
34
     * @var array
35
     */
36
    protected $createFields = ['invite_hash', 'company_id', 'role_id', 'app_id', 'email'];
37
38
    /*
39
     * fields we accept to create
40
     *
41
     * @var array
42
     */
43
    protected $updateFields = ['invite_hash', 'company_id', 'role_id', 'app_id', 'email'];
44
45
    /**
46
     * set objects
47
     *
48
     * @return void
49
     */
50 1
    public function onConstruct()
51
    {
52 1
        $this->model = new UsersInvite();
53 1
    }
54
55
    /**
56
     * Sets up invitation information for a would be user
57
     * @return Response
58
     */
59 1
    public function insertInvite(): Response
60
    {
61 1
        $request = $this->request->getPost();
62 1
        $random = new Random();
63
64 1
        $validation = new Validation();
65 1
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
66 1
        $validation->add('role', new PresenceOf(['message' => _('The role is required.')]));
67
68
        //validate this form for password
69 1
        $messages = $validation->validate($this->request->getPost());
70 1
        if (count($messages)) {
71
            foreach ($messages as $message) {
72
                throw new ServerErrorHttpException((string)$message);
73
            }
74
        }
75
76
        //Save data to users_invite table and generate a hash for the invite
77 1
        $userInvite = $this->model;
78 1
        $userInvite->company_id = $this->userData->default_company;
79 1
        $userInvite->app_id = $this->app->getId();
80 1
        $userInvite->role_id = $request['role'] == 'Admins' ? 1 : 2;
81 1
        $userInvite->email = $request['email'];
82 1
        $userInvite->invite_hash = $random->base58();
83 1
        $userInvite->created_at = date('Y-m-d H:m:s');
84
85 1
        if (!$userInvite->save()) {
86
            throw new UnprocessableEntityHttpException((string) current($userInvite->getMessages()));
87
        }
88
89 1
        $userInviteArray = $userInvite->toArray();
90
91
        //Fetch email template of user
92 1
        $emailTemplate = EmailTemplates::findFirst([
93 1
            'conditions' => 'users_id = ?0 and company_id = ?1 and app_id = ?2 and is_deleted = 0',
94 1
            'bind' => [$this->userData->getId(), $this->userData->default_company, $this->app->getId()]
95
        ]);
96
97 1
        if (!is_object($emailTemplate)) {
98
            throw new NotFoundHttpException('Email Template not found');
99
        }
100
101
        // Lets send the mail
102
103 1
        $invitationUrl = $this->config->app->frontEndUrl . 'user-invite/' . $userInviteArray['invite_hash'];
104
105 1
        if (!defined('API_TESTS')) {
106
            $subject = _('You have been invited!');
107
            $this->mail
108
            ->to($userInviteArray['email'])
109
            ->subject($subject)
110
            ->params($invitationUrl)
111
            ->content($emailTemplate->template)
112
            ->sendNow();
113
        }
114
115 1
        return $this->response($userInviteArray);
116
    }
117
118
    /**
119
     * Add invited user to our system
120
     * @return Response
121
     */
122 1
    public function processUserInvite(string $hash): Response
123
    {
124 1
        $request = $this->request->getPost();
125
126 1
        if (empty($request)) {
127
            $request = $this->request->getJsonRawBody(true);
128
        }
129
130
        //Ok let validate user password
131 1
        $validation = new Validation();
132 1
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
133
134 1
        $validation->add(
135 1
            'password',
136 1
            new StringLength([
137 1
                'min' => 8,
138 1
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
139
            ])
140
        );
141
142
        //validate this form for password
143 1
        $messages = $validation->validate($request);
144 1
        if (count($messages)) {
145
            foreach ($messages as $message) {
146
                throw new ServerErrorHttpException((string)$message);
147
            }
148
        }
149
150
        //Lets find users_invite by hash on our database
151 1
        $usersInvite = $this->model::findFirst([
152 1
                'conditions' => 'invite_hash = ?0 and is_deleted = 0',
153 1
                'bind' => [$hash]
154
            ]);
155
156 1
        if (!is_object($usersInvite)) {
157
            throw new NotFoundHttpException('Users Invite not found');
158
        }
159
160 1
        $newUser = new Users();
161 1
        $newUser->firstname = $request['firstname'];
162 1
        $newUser->lastname = $request['lastname'];
163 1
        $newUser->displayname = $request['displayname'];
164 1
        $newUser->password = $request['password'];
165 1
        $newUser->email = $usersInvite->email;
166 1
        $newUser->user_active = 1;
167 1
        $newUser->roles_id = $usersInvite->role_id;
168 1
        $newUser->created_at = date('Y-m-d H:m:s');
169
        // $newUser->name = $this->userData->defaultCompany; //Como puedo agregar este campo si es de una relacion ?
170 1
        $newUser->default_company = $this->userData->default_company;
171
172
        //Lets insert the new user to our system.
173
174 1
        if ($newUser->save()) {
175 1
            return $this->response($newUser->toArray());
176
        } else {
177
            //if not thorw exception
178
            throw new UnprocessableEntityHttpException((string) current($newUser->getMessages()));
179
        }
180
    }
181
}
182