Completed
Push — develop ( eed049...0ceb6c )
by Nate
01:42
created

OrganizationRelationship::resolveOrganization()   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\relationships;
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
use Tightenco\Collect\Support\Collection;
21
22
/**
23
 * Manages Organizations associated to Users
24
 *
25
 * @author Flipbox Factory <[email protected]>
26
 * @since 2.0.0
27
 * *
28
 * @method UserAssociation findOrCreate($object)
29
 * @method UserAssociation findOne($object = null)
30
 * @method UserAssociation findOrFail($object)
31
 */
32
class OrganizationRelationship implements RelationshipInterface
33
{
34
    use RelationshipTrait;
35
36
    /**
37
     * @var User
38
     */
39
    private $user;
40
41
    /**
42
     * @param User $user
43
     */
44
    public function __construct(User $user)
45
    {
46
        $this->user = $user;
47
    }
48
49
50
    /************************************************************
51
     * COLLECTION
52
     ************************************************************/
53
54
    /**
55
     * Get a collection of associated organizations
56
     *
57
     * @return Organization[]|Collection
58
     */
59
    public function getCollection(): Collection
60
    {
61
        $query = Organization::find()
62
            ->user($this->user)
63
            ->orderBy([
64
                'organizationOrder' => SORT_ASC
65
            ]);
66
67
        if (null === $this->collection) {
68
            return Collection::make(
69
                $query->all()
70
            );
71
        };
72
73
        return Collection::make(
74
            $query
75
                ->id($this->collection->sortBy('organizationOrder')->pluck('organizationId'))
0 ignored issues
show
Documentation introduced by
$this->collection->sortB...pluck('organizationId') is of type object<Tightenco\Collect\Support\Collection>, but the function expects a integer|array<integer,integer>|false|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
                ->fixedOrder(true)
77
                ->limit(null)
78
                ->all()
79
        );
80
    }
81
82
83
    /************************************************************
84
     * QUERY
85
     ************************************************************/
86
87
    /**
88
     * @param array $criteria
89
     * @return UserAssociationQuery
90
     */
91
    protected function query(array $criteria = []): UserAssociationQuery
92
    {
93
        /** @noinspection PhpUndefinedMethodInspection */
94
        $query = UserAssociation::find()
95
            ->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...
96
            ->orderBy([
97
                'organizationOrder' => SORT_ASC
98
            ]);
99
100
        if (!empty($criteria)) {
101
            QueryHelper::configure(
102
                $query,
103
                $criteria
104
            );
105
        }
106
107
        return $query;
108
    }
109
110
    /**
111
     * @param $object
112
     * @return UserAssociation
113
     */
114
    protected function create($object): UserAssociation
115
    {
116
        return (new UserAssociation())
117
            ->setOrganization($this->resolveOrganization($object))
118
            ->setUser($this->user);
119
    }
120
121
    /**
122
     * @inheritDoc
123
     *
124
     * @param bool $addToOrganization
125
     */
126
    public function addOne(
127
        $object,
128
        array $attributes = [],
129
        bool $addToOrganization = false
130
    ): RelationshipInterface {
131
        if (null === ($association = $this->findOne($object))) {
132
            $association = $this->create($object);
133
            $this->addToCollection($association);
134
        }
135
136
        if (!empty($attributes)) {
137
            Craft::configure(
138
                $association,
139
                $attributes
140
            );
141
        }
142
143
        // Add user to organization as well?
144
        if ($addToOrganization && $association->getOrganization()->getId() !== null) {
145
            $association->getOrganization()->getUsers()->add($this->user);
146
        }
147
148
        return $this;
149
    }
150
151
    /*******************************************
152
     * SAVE
153
     *******************************************/
154
155
    /**
156
     * @inheritDoc
157
     */
158
    protected function associationDelta(): array
159
    {
160
        $existingAssociations = $this->query()
161
            ->indexBy('organizationId')
162
            ->all();
163
164
        $associations = [];
165
        $order = 1;
166
167
        /** @var UserAssociation $newAssociation */
168
        foreach ($this->getRelationships()->sortBy('organizationOrder') as $newAssociation) {
169
            if (null === ($association = ArrayHelper::remove(
170
                $existingAssociations,
171
                $newAssociation->getOrganizationId()
172
            ))) {
173
                $association = $newAssociation;
174
            } elseif ($newAssociation->getTypes()->isMutated()) {
175
                /** @var UserAssociation $association */
176
                $association->getTypes()->clear()->add(
177
                    $newAssociation->getTypes()->getCollection()
178
                );
179
            }
180
181
            $association->userOrder = $newAssociation->userOrder;
182
            $association->organizationOrder = $order++;
183
            $association->state = $newAssociation->state;
184
185
            $associations[] = $association;
186
        }
187
188
        return [$associations, $existingAssociations];
189
    }
190
191
    /**
192
     * @inheritDoc
193
     */
194
    protected function handleAssociationError()
195
    {
196
        $this->user->addError('organizations', 'Unable to save user organizations.');
197
    }
198
199
200
    /*******************************************
201
     * UTILS
202
     *******************************************/
203
204
    /**
205
     * @param UserAssociation|Organization|int|array|null $object
206
     * @return int|null
207
     */
208
    protected function findKey($object = null)
209
    {
210
        if (null === ($element = $this->resolveOrganization($object))) {
211
            Organizations::info(sprintf(
212
                "Unable to resolve organization: %s",
213
                (string)Json::encode($object)
214
            ));
215
            return null;
216
        }
217
218
        foreach ($this->findAll() as $key => $association) {
0 ignored issues
show
Deprecated Code introduced by
The method flipbox\organizations\re...ionshipTrait::findAll() has been deprecated with message: use `getCollection()`

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
219
            if ($association->getOrganizationId() == $element->getId()) {
220
                return $key;
221
            }
222
        }
223
224
        return null;
225
    }
226
227
    /**
228
     * @param UserAssociation|Organization|int|array|null $organization
229
     * @return Organization|null
230
     */
231
    protected function resolveOrganization($organization = null)
232
    {
233
        if (null === $organization) {
234
            return null;
235
        }
236
237
        if ($organization instanceof UserAssociation) {
238
            return $organization->getOrganization();
239
        }
240
241
        if ($organization instanceof Organization) {
242
            return $organization;
243
        }
244
245
        if (is_array($organization) &&
246
            null !== ($id = ArrayHelper::getValue($organization, 'id'))
247
        ) {
248
            $organization = ['id' => $id];
249
        }
250
251
        return Organization::findOne($organization);
252
    }
253
}
254