Completed
Push — develop ( e5b284...0f5a88 )
by Nate
05:39
created

OrganizationRelationship::getCollection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 20
cp 0
rs 9.568
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 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\relationships;
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
use Tightenco\Collect\Support\Collection;
20
21
/**
22
 * Manages Organizations associated to Users
23
 *
24
 * @author Flipbox Factory <[email protected]>
25
 * @since 2.0.0
26
 * *
27
 * @method UserAssociation findOrCreate($object)
28
 * @method UserAssociation findOne($object = null)
29
 * @method UserAssociation findOrFail($object)
30
 */
31
class OrganizationRelationship implements RelationshipInterface
32
{
33
    use RelationshipTrait;
34
35
    /**
36
     * @var User
37
     */
38
    private $user;
39
40
    /**
41
     * @param User $user
42
     */
43
    public function __construct(User $user)
44
    {
45
        $this->user = $user;
46
    }
47
48
49
    /************************************************************
50
     * COLLECTION
51
     ************************************************************/
52
53
    /**
54
     * Get a collection of associated organizations
55
     *
56
     * @return Organization[]|Collection
57
     */
58
    public function getCollection(): Collection
59
    {
60
        $query = Organization::find()
61
            ->user($this->user)
62
            ->orderBy([
63
                'organizationOrder' => SORT_ASC
64
            ]);
65
66
        if (null === $this->relations) {
67
            return Collection::make(
68
                $query->all()
69
            );
70
        };
71
72
        return Collection::make(
73
            $query
74
                ->id($this->relations->sortBy('organizationOrder')->pluck('organizationId'))
0 ignored issues
show
Documentation introduced by
$this->relations->sortBy...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...
75
                ->fixedOrder(true)
76
                ->limit(null)
77
                ->all()
78
        );
79
    }
80
81
82
    /************************************************************
83
     * QUERY
84
     ************************************************************/
85
86
    /**
87
     * @param array $criteria
88
     * @return UserAssociationQuery
89
     */
90
    protected function query(array $criteria = []): UserAssociationQuery
91
    {
92
        /** @noinspection PhpUndefinedMethodInspection */
93
        $query = UserAssociation::find()
94
            ->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...
95
            ->orderBy([
96
                'organizationOrder' => SORT_ASC
97
            ]);
98
99
        if (!empty($criteria)) {
100
            QueryHelper::configure(
101
                $query,
102
                $criteria
103
            );
104
        }
105
106
        return $query;
107
    }
108
109
    /**
110
     * @param $object
111
     * @return UserAssociation
112
     */
113
    protected function create($object): UserAssociation
114
    {
115
        return (new UserAssociation())
116
            ->setOrganization($this->resolveOrganization($object))
117
            ->setUser($this->user);
118
    }
119
120
121
    /*******************************************
122
     * SAVE
123
     *******************************************/
124
125
    /**
126
     * @inheritDoc
127
     */
128
    protected function associationDelta(): array
129
    {
130
        $existingAssociations = $this->query()
131
            ->indexBy('organizationId')
132
            ->all();
133
134
        $associations = [];
135
        $order = 1;
136
137
        /** @var UserAssociation $newAssociation */
138
        foreach ($this->getRelationships()->sortBy('organizationOrder') as $newAssociation) {
139
            if (null === ($association = ArrayHelper::remove(
140
                    $existingAssociations,
141
                    $newAssociation->getOrganizationId()
142
                ))) {
143
                $association = $newAssociation;
144
            } elseif ($newAssociation->getTypes()->isMutated()) {
145
                /** @var UserAssociation $association */
146
                $association->getTypes()->clear()->add(
147
                    $newAssociation->getTypes()->getCollection()
148
                );
149
            }
150
151
            $association->userOrder = $newAssociation->userOrder;
152
            $association->organizationOrder = $order++;
153
            $association->state = $newAssociation->state;
154
155
            $associations[] = $association;
156
        }
157
158
        return [$associations, $existingAssociations];
159
    }
160
161
    /**
162
     * @inheritDoc
163
     */
164
    protected function handleAssociationError()
165
    {
166
        $this->user->addError('organizations', 'Unable to save user organizations.');
167
    }
168
169
170
    /*******************************************
171
     * UTILS
172
     *******************************************/
173
174
    /**
175
     * @param UserAssociation|Organization|int|array|null $object
176
     * @return int|null
177
     */
178
    protected function findKey($object = null)
179
    {
180
        if (null === ($element = $this->resolveOrganization($object))) {
181
            Organizations::info(sprintf(
182
                "Unable to resolve organization: %s",
183
                (string)Json::encode($object)
184
            ));
185
            return null;
186
        }
187
188
        /** @var UserAssociation $association */
189
        foreach ($this->getRelationships()->all() as $key => $association) {
190
            if ($association->getOrganizationId() == $element->getId()) {
191
                return $key;
192
            }
193
        }
194
195
        return null;
196
    }
197
198
    /**
199
     * @param UserAssociation|Organization|int|array|null $organization
200
     * @return Organization|null
201
     */
202
    protected function resolveOrganization($organization = null)
203
    {
204
        if (null === $organization) {
205
            return null;
206
        }
207
208
        if ($organization instanceof UserAssociation) {
209
            return $organization->getOrganization();
210
        }
211
212
        if ($organization instanceof Organization) {
213
            return $organization;
214
        }
215
216
        if (is_array($organization) &&
217
            null !== ($id = ArrayHelper::getValue($organization, 'id'))
218
        ) {
219
            $organization = ['id' => $id];
220
        }
221
222
        return Organization::findOne($organization);
223
    }
224
}
225