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

OrganizationsToUserAssociatedManager   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 173
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 10
dl 0
loc 173
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 4
B resolveOrganization() 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 Organizations associated to Users
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 OrganizationsToUserAssociatedManager
35
{
36
    use AssociationManagerTrait;
37
38
    /**
39
     * @var User
40
     */
41
    private $user;
42
43
    /**
44
     * @param User $user
45
     */
46
    public function __construct(User $user)
47
    {
48
        $this->user = $user;
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
            ->setUserId($this->user->getId() ?: false)
0 ignored issues
show
Security Bug introduced by
It seems like $this->user->getId() ?: false can also be of type false; however, flipbox\craft\ember\quer...ibuteTrait::setUserId() does only seem to accept string|array<integer,str...ft\elements\User>>|null, did you maybe forget to handle an error condition?
Loading history...
60
            ->orderBy([
61
                'organizationOrder' => 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->resolveOrganization($object))
82
            ->setUser($this->user);
83
    }
84
85
    /**
86
     * @inheritDoc
87
     *
88
     * @param bool $addToOrganization
89
     */
90
    public function addOne($object, array $attributes = [], bool $addToOrganization = 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 organization as well?
105
        if ($addToOrganization && $association->getOrganization()->getId() !== null) {
106
            $association->getOrganization()->getUserManager()->addOne($this->user, [], false);
107
        }
108
109
        return $this;
110
    }
111
112
    /*******************************************
113
     * SAVE
114
     *******************************************/
115
116
    /**
117
     * @inheritDoc
118
     */
119
    protected function associationDelta(): array
120
    {
121
        $existingAssociations = $this->query()
122
            ->indexBy('organizationId')
123
            ->all();
124
125
        $associations = [];
126
        $order = 1;
127
        foreach ($this->findAll() as $newAssociation) {
128
            if (null === ($association = ArrayHelper::remove(
129
                $existingAssociations,
130
                $newAssociation->getOrganizationId()
131
            ))) {
132
                $association = $newAssociation;
133
            }
134
135
            $association->userOrder = $newAssociation->userOrder;
136
            $association->organizationOrder = $order++;
137
138
            $associations[] = $association;
139
        }
140
141
        return [$associations, $existingAssociations];
142
    }
143
144
    /**
145
     * @inheritDoc
146
     */
147
    protected function handleAssociationError()
148
    {
149
        $this->user->addError('organizations', 'Unable to save user organizations.');
150
    }
151
152
153
    /*******************************************
154
     * UTILS
155
     *******************************************/
156
157
    /**
158
     * @param UserAssociation|Organization|int|array|null $object
159
     * @return int|null
160
     */
161
    protected function findKey($object = null)
162
    {
163
        if (null === ($element = $this->resolveOrganization($object))) {
164
            Organizations::info(sprintf(
165
                "Unable to resolve organization: %s",
166
                (string)Json::encode($object)
167
            ));
168
            return null;
169
        }
170
171
        foreach ($this->findAll() as $key => $association) {
172
            if ($association->getOrganizationId() == $element->getId()) {
173
                return $key;
174
            }
175
        }
176
177
        return null;
178
    }
179
180
    /**
181
     * @param UserAssociation|Organization|int|array|null $organization
182
     * @return Organization|null
183
     */
184
    protected function resolveOrganization($organization = null)
185
    {
186
        if (null === $organization) {
187
            return null;
188
        }
189
190
        if ($organization instanceof UserAssociation) {
191
            return $organization->getOrganization();
192
        }
193
194
        if ($organization instanceof Organization) {
195
            return $organization;
196
        }
197
198
        if (is_array($organization) &&
199
            null !== ($id = ArrayHelper::getValue($organization, 'id'))
200
        ) {
201
            $organization = ['id' => $id];
202
        }
203
204
        return Organization::findOne($organization);
205
    }
206
}
207