Completed
Push — develop ( fec580...e0c8ea )
by Nate
02:55
created

UsersToOrganizationAssociatedManager   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 10
dl 0
loc 174
ccs 0
cts 100
cp 0
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A query() 0 18 3
A create() 0 6 1
A addOne() 0 21 5
A associationDelta() 0 24 3
A handleAssociationError() 0 4 1
A findKey() 0 18 5
B resolveUser() 0 22 6
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;
12
use craft\elements\User;
13
use craft\helpers\ArrayHelper;
14
use craft\helpers\Json;
15
use flipbox\craft\ember\helpers\QueryHelper;
16
use flipbox\organizations\elements\Organization;
17
use flipbox\organizations\Organizations;
18
use flipbox\organizations\queries\UserAssociationQuery;
19
use flipbox\organizations\records\UserAssociation;
20
21
/**
22
 * Manages Users associated to Organizations
23
 *
24
 * @author Flipbox Factory <[email protected]>
25
 * @since 1.1.0
26
 *
27
 * @property UserAssociation[] $associations
28
 *
29
 * @method UserAssociation findOrCreate($object)
30
 * @method UserAssociation[] findAll()
31
 * @method UserAssociation findOne($object = null)
32
 * @method UserAssociation findOrFail($object)
33
 */
34
class UsersToOrganizationAssociatedManager
35
{
36
    use AssociationManagerTrait;
37
38
    /**
39
     * @var Organization
40
     */
41
    private $organization;
42
43
    /**
44
     * @param Organization $organization
45
     */
46
    public function __construct(Organization $organization)
47
    {
48
        $this->organization = $organization;
49
    }
50
51
    /**
52
     * @param array $criteria
53
     * @return UserAssociationQuery
54
     */
55
    public function query(array $criteria = []): UserAssociationQuery
56
    {
57
        /** @noinspection PhpUndefinedMethodInspection */
58
        $query = UserAssociation::find()
59
            ->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...
60
            ->orderBy([
61
                'userOrder' => SORT_ASC
62
            ]);
63
64
        if (!empty($criteria)) {
65
            QueryHelper::configure(
66
                $query,
67
                $criteria
68
            );
69
        }
70
71
        return $query;
72
    }
73
74
    /**
75
     * @param $object
76
     * @return UserAssociation
77
     */
78
    public function create($object): UserAssociation
79
    {
80
        return (new UserAssociation())
81
            ->setOrganization($this->organization)
82
            ->setUser($this->resolveUser($object));
83
    }
84
85
    /**
86
     * @inheritDoc
87
     *
88
     * @param bool $addToUser
89
     */
90
    public function addOne($object, array $attributes = [], bool $addToUser = false)
91
    {
92
        if (null === ($association = $this->findOne($object))) {
93
            $association = $this->create($object);
94
            $this->addToCache($association);
95
        }
96
97
        if (!empty($attributes)) {
98
            Craft::configure(
99
                $association,
100
                $attributes
101
            );
102
        }
103
104
        // Add user to user as well?
105
        if ($addToUser && $association->getUser()->getId() !== null) {
106
            $association->getUser()->getOrganizationManager()->addOne($this->organization, [], false);
107
        }
108
109
        return $this;
110
    }
111
112
113
    /*******************************************
114
     * SAVE
115
     *******************************************/
116
117
    /**
118
     * @inheritDoc
119
     */
120
    protected function associationDelta(): array
121
    {
122
        $existingAssociations = $this->query()
123
            ->indexBy('userId')
124
            ->all();
125
126
        $associations = [];
127
        $order = 1;
128
        foreach ($this->findAll() as $newAssociation) {
129
            if (null === ($association = ArrayHelper::remove(
130
                $existingAssociations,
131
                $newAssociation->getUserId()
132
            ))) {
133
                $association = $newAssociation;
134
            }
135
136
            $association->userOrder = $order++;
137
            $association->organizationOrder = $newAssociation->organizationOrder;
138
139
            $associations[] = $association;
140
        }
141
142
        return [$associations, $existingAssociations];
143
    }
144
145
    /**
146
     * @inheritDoc
147
     */
148
    protected function handleAssociationError()
149
    {
150
        $this->organization->addError('users', 'Unable to save user organizations.');
151
    }
152
153
154
    /*******************************************
155
     * UTILS
156
     *******************************************/
157
158
    /**
159
     * @param UserAssociation|User|int|array|null $object
160
     * @return int|null
161
     */
162
    protected function findKey($object = null)
163
    {
164
        if (null === ($element = $this->resolveUser($object))) {
165
            Organizations::info(sprintf(
166
                "Unable to resolve user: %s",
167
                (string)Json::encode($object)
168
            ));
169
            return null;
170
        }
171
172
        foreach ($this->findAll() as $key => $association) {
173
            if (null !== $association->getUser() && $association->getUser()->email == $element->email) {
174
                return $key;
175
            }
176
        }
177
178
        return null;
179
    }
180
181
    /**
182
     * @param UserAssociation|User|int|array|null $user
183
     * @return User|null
184
     */
185
    protected function resolveUser($user = null)
186
    {
187
        if (null === $user) {
188
            return null;
189
        }
190
191
        if ($user instanceof UserAssociation) {
192
            return $user->getUser();
193
        }
194
195
        if ($user instanceof User) {
196
            return $user;
197
        }
198
199
        if (is_array($user) &&
200
            null !== ($id = ArrayHelper::getValue($user, 'id'))
201
        ) {
202
            $user = ['id' => $id];
203
        }
204
205
        return User::findOne($user);
206
    }
207
}
208