Failed Conditions
Pull Request — master (#55)
by Rafael
06:42
created

UsersAssociatedTrait::associate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0023

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 2
dl 0
loc 16
ccs 11
cts 12
cp 0.9167
crap 2.0023
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Traits;
6
7
use Gewaer\Models\Users;
8
use Gewaer\Models\Roles;
9
use Gewaer\Models\Companies;
10
use Exception;
11
12
/**
13
 * Trait ResponseTrait
14
 *
15
 * @package Gewaer\Traits
16
 *
17
 * @property Users $user
18
 * @property Config $config
19
 * @property Request $request
20
 * @property Auth $auth
21
 * @property \Phalcon\Di $di
22
 * @property Roles $roles_id
23
 *
24
 */
25
trait UsersAssociatedTrait
26
{
27
    /**
28
     * create new related User Associated instance dynamicly
29
     * @param Users $user
30
     * @param Companies $company
31
     * @return void
32
     * @todo Find a better way to handle namespaces for models
33
     */
34 4
    public function associate(Users $user, Companies $company): array
35
    {
36 4
        $class = str_replace('UsersAssociated\\', 'UsersAssociated', substr_replace(get_class($this), '\UsersAssociated', strrpos(get_class($this), '\\'), 0));
37 4
        $usersAssociatedModel = new $class();
38 4
        $usersAssociatedModel->users_id = $user->getId();
39 4
        $usersAssociatedModel->companies_id = $company->getId();
40 4
        $usersAssociatedModel->apps_id = $this->di->getApp()->getId();
41 4
        $usersAssociatedModel->identify_id = $user->getId();
42 4
        $usersAssociatedModel->user_active = 1;
43 4
        $usersAssociatedModel->user_role = Roles::existsById((int)$user->roles_id)->name;
44
45 4
        if (!$usersAssociatedModel->save()) {
46
            throw new Exception((string)current($usersAssociatedModel->getMessages()));
47
        }
48
49 4
        return $usersAssociatedModel->toArray();
50
    }
51
}
52