Completed
Push — develop ( 485964...fec580 )
by Nate
04:06
created

resolveUser()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 8.9457
c 0
b 0
f 0
cc 6
nc 5
nop 1
crap 42
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/organization/license
6
 * @link       https://www.flipboxfactory.com/software/organization/
7
 */
8
9
namespace flipbox\organizations\managers;
10
11
use craft\elements\User;
12
use craft\helpers\ArrayHelper;
13
use craft\helpers\Json;
14
use flipbox\craft\ember\helpers\QueryHelper;
15
use flipbox\organizations\elements\Organization;
16
use flipbox\organizations\Organizations;
17
use flipbox\organizations\queries\UserAssociationQuery;
18
use flipbox\organizations\records\UserAssociation;
19
20
/**
21
 * Manages Users associated to Organizations
22
 *
23
 * @author Flipbox Factory <[email protected]>
24
 * @since 1.1.0
25
 *
26
 * @property UserAssociation[] $associations
27
 *
28
 * @method UserAssociation findOrCreate($object)
29
 * @method UserAssociation[] findAll()
30
 * @method UserAssociation findOne()
31
 * @method UserAssociation findOrFail()
32
 */
33
class UsersToOrganizationAssociatedManager
34
{
35
    use AssociationManagerTrait;
36
37
    /**
38
     * @var Organization
39
     */
40
    private $organization;
41
42
    /**
43
     * @param Organization $organization
44
     */
45
    public function __construct(Organization $organization)
46
    {
47
        $this->organization = $organization;
48
    }
49
50
    /**
51
     * @param array $criteria
52
     * @return UserAssociationQuery
53
     */
54
    public function query(array $criteria = []): UserAssociationQuery
55
    {
56
        /** @noinspection PhpUndefinedMethodInspection */
57
        $query = UserAssociation::find()
58
            ->setOrganizationId($this->organization->getId() ?: false)
0 ignored issues
show
Security Bug introduced by
It seems like $this->organization->getId() ?: false can also be of type false; however, flipbox\organizations\qu...it::setOrganizationId() does only seem to accept string|array<integer,str...nts\Organization>>|null, did you maybe forget to handle an error condition?
Loading history...
59
            ->orderBy([
60
                'userOrder' => SORT_ASC
61
            ]);
62
63
        if (!empty($criteria)) {
64
            QueryHelper::configure(
65
                $query,
66
                $criteria
67
            );
68
        }
69
70
        return $query;
71
    }
72
73
    /**
74
     * @param $object
75
     * @return UserAssociation
76
     */
77
    public function create($object): UserAssociation
78
    {
79
        return (new UserAssociation())
80
            ->setOrganization($this->organization)
81
            ->setUser($this->resolveUser($object));
82
    }
83
84
85
    /*******************************************
86
     * SAVE
87
     *******************************************/
88
89
    /**
90
     * @inheritDoc
91
     */
92
    protected function associationDelta(): array
93
    {
94
        $existingAssociations = $this->query()
95
            ->indexBy('userId')
96
            ->all();
97
98
        $associations = [];
99
        $order = 1;
100
        foreach ($this->findAll() as $newAssociation) {
101
            if (null === ($association = ArrayHelper::remove(
102
                $existingAssociations,
103
                $newAssociation->getUserId()
104
            ))) {
105
                $association = $newAssociation;
106
            }
107
108
            $association->userOrder = $order++;
109
            $association->organizationOrder = $newAssociation->organizationOrder;
110
111
            $associations[] = $association;
112
        }
113
114
        return [$associations, $existingAssociations];
115
    }
116
117
    /**
118
     * @inheritDoc
119
     */
120
    protected function handleAssociationError()
121
    {
122
        $this->organization->addError('users', 'Unable to save user organizations.');
123
    }
124
125
126
    /*******************************************
127
     * UTILS
128
     *******************************************/
129
130
    /**
131
     * @param UserAssociation|User|int|array|null $object
132
     * @return int|null
133
     */
134
    protected function findKey($object = null)
135
    {
136
        if (null === ($element = $this->resolveUser($object))) {
137
            Organizations::info(sprintf(
138
                "Unable to resolve user: %s",
139
                (string)Json::encode($object)
140
            ));
141
            return null;
142
        }
143
144
        foreach ($this->findAll() as $key => $association) {
145
            if (null !== $association->getUser() && $association->getUser()->email == $element->email) {
146
                return $key;
147
            }
148
        }
149
150
        return null;
151
    }
152
153
    /**
154
     * @param UserAssociation|User|int|array|null $user
155
     * @return User|null
156
     */
157
    protected function resolveUser($user = null)
158
    {
159
        if (null === $user) {
160
            return null;
161
        }
162
163
        if ($user instanceof UserAssociation) {
164
            return $user->getUser();
165
        }
166
167
        if ($user instanceof User) {
168
            return $user;
169
        }
170
171
        if (is_array($user) &&
172
            null !== ($id = ArrayHelper::getValue($user, 'id'))
173
        ) {
174
            $user = ['id' => $id];
175
        }
176
177
        return User::findOne($user);
178
    }
179
}
180