Completed
Push — develop ( 0d3736...607e7f )
by Nate
09:29
created

UsersController::actionAssociationEditorHtml()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 0
cts 27
cp 0
rs 9.44
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 12
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\cp\controllers;
10
11
use Craft;
12
use craft\elements\User;
13
use craft\helpers\ArrayHelper;
14
use flipbox\organizations\actions\users\AssociateUserToOrganization;
15
use flipbox\organizations\actions\users\DissociateUserFromOrganization;
16
use flipbox\organizations\behaviors\UserTypesBehavior;
17
use flipbox\organizations\events\handlers\RegisterOrganizationUserElementDefaultTableAttributes;
18
use flipbox\organizations\events\handlers\RegisterOrganizationUserElementTableAttributes;
19
use flipbox\organizations\events\handlers\SetOrganizationUserElementTableAttributeHtml;
20
use flipbox\organizations\records\UserAssociation;
21
use flipbox\organizations\records\UserType;
22
use yii\base\Event;
23
24
/**
25
 * @author Flipbox Factory <[email protected]>
26
 * @since 1.0.0
27
 */
28
class UsersController extends AbstractController
29
{
30
    /**
31
     * @return array
32
     */
33
    public function behaviors()
34
    {
35
        return ArrayHelper::merge(
36
            parent::behaviors(),
37
            [
38
                'error' => [
39
                    'default' => 'organization'
40
                ],
41
                'redirect' => [
42
                    'only' => ['associate', 'dissociate'],
43
                    'actions' => [
44
                        'associate' => [204],
45
                        'dissociate' => [204],
46
                    ]
47
                ],
48
                'flash' => [
49
                    'actions' => [
50
                        'associate' => [
51
                            204 => Craft::t('organizations', "Successfully associated user."),
52
                            401 => Craft::t('organizations', "Failed to associate user.")
53
                        ],
54
                        'dissociate' => [
55
                            204 => Craft::t('organizations', "Successfully dissociated user."),
56
                            401 => Craft::t('organizations', "Failed to dissociate user.")
57
                        ]
58
                    ]
59
                ]
60
            ]
61
        );
62
    }
63
64
    /**
65
     * @return array
66
     */
67
    protected function verbs(): array
68
    {
69
        return [
70
            'associate' => ['post']
71
        ];
72
    }
73
74
    /**
75
     * @param int|string|null $user
76
     * @param int|string|null $organization
77
     * @return mixed
78
     * @throws \yii\base\InvalidConfigException
79
     */
80
    public function actionAssociate($user = null, $organization = null)
81
    {
82
        if (null === $organization) {
83
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
84
        }
85
86
        if (null === $user) {
87
            $user = Craft::$app->getRequest()->getBodyParam('user');
88
        }
89
90
        /** @var AssociateUserToOrganization $action */
91
        $action = Craft::createObject([
92
            'class' => AssociateUserToOrganization::class
93
        ], [
94
            'associate',
95
            $this
96
        ]);
97
98
        return $action->runWithParams([
99
            'organization' => $organization,
100
            'user' => $user
101
        ]);
102
    }
103
104
    /**
105
     * @param int|string|null $user
106
     * @param int|string|null $organization
107
     * @return mixed
108
     * @throws \yii\base\InvalidConfigException
109
     */
110
    public function actionDissociate($user = null, $organization = null)
111
    {
112
        if (null === $organization) {
113
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
114
        }
115
116
        if (null === $user) {
117
            $user = Craft::$app->getRequest()->getBodyParam('user');
118
        }
119
120
        /** @var DissociateUserFromOrganization $action */
121
        $action = Craft::createObject([
122
            'class' => DissociateUserFromOrganization::class
123
        ], [
124
            'dissociate',
125
            $this
126
        ]);
127
128
        return $action->runWithParams([
129
            'organization' => $organization,
130
            'user' => $user
131
        ]);
132
    }
133
134
    /**
135
     * @param null $user
136
     * @param null $organization
137
     * @return \yii\web\Response
138
     * @throws \Throwable
139
     * @throws \yii\db\StaleObjectException
140
     */
141
    public function actionSaveAssociation($user = null, $organization = null)
142
    {
143
        if (null === $organization) {
144
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
145
        }
146
147
        if (null === $user) {
148
            $user = Craft::$app->getRequest()->getBodyParam(
149
                'user',
150
                Craft::$app->getRequest()->getBodyParam('elementId')
151
            );
152
        }
153
154
        $userAssociation = UserAssociation::findOne([
155
            'user' => $user,
156
            'organization' => $organization
157
        ]);
158
159
        $success = true;
160
161
        $userAssociation->state = Craft::$app->getRequest()->getBodyParam('state', $userAssociation->state);
162
163
        if (!$userAssociation->save(true, ['state'])) {
164
            $success = false;
165
        }
166
167
        $user = $userAssociation->getUser();
168
169
        if (null !== ($types = Craft::$app->getRequest()->getBodyParam('types'))) {
170
            $query = UserType::find()->id(empty($types) ? ':empty:' : $types);
171
172
            $query->setCachedResult(
173
                $query->all()
174
            );
175
176
            /** @var UserTypesBehavior|User $user */
177
            if (!$user->saveUserTypes($query, $userAssociation->getOrganization())) {
0 ignored issues
show
Bug introduced by
The method saveUserTypes does only exist in flipbox\organizations\behaviors\UserTypesBehavior, but not in craft\elements\User.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
178
                $success = false;
179
180
                $userAssociation->addError('types', 'Unable to save types.');
181
            }
182
        }
183
184
        $response = [
185
            'success' => $success,
186
            'id' => $user->getId(),
187
            'newTitle' => (string)$user,
188
            'cpEditUrl' => $user->getCpEditUrl(),
189
        ];
190
191
        // Should we be including table attributes too?
192
        $sourceKey = Craft::$app->getRequest()->getBodyParam('includeTableAttributesForSource');
193
194
        if ($sourceKey) {
195
            Event::on(
196
                User::class,
197
                User::EVENT_REGISTER_DEFAULT_TABLE_ATTRIBUTES,
198
                [
199
                    RegisterOrganizationUserElementDefaultTableAttributes::class,
200
                    'handle'
201
                ]
202
            );
203
204
            // Add attributes the user index
205
            Event::on(
206
                User::class,
207
                User::EVENT_REGISTER_TABLE_ATTRIBUTES,
208
                [
209
                    RegisterOrganizationUserElementTableAttributes::class,
210
                    'handle'
211
                ]
212
            );
213
214
            // Add 'organizations' on the user html element
215
            Event::on(
216
                User::class,
217
                User::EVENT_SET_TABLE_ATTRIBUTE_HTML,
218
                [
219
                    SetOrganizationUserElementTableAttributeHtml::class,
220
                    'handle'
221
                ]
222
            );
223
224
            $attributes = Craft::$app->getElementIndexes()->getTableAttributes(get_class($user), $sourceKey);
225
226
            // Drop the first one
227
            array_shift($attributes);
228
229
            foreach ($attributes as $attribute) {
230
                $response['tableAttributes'][$attribute[0]] = $user->getTableAttributeHtml($attribute[0]);
231
            }
232
233
            Event::off(
234
                User::class,
235
                User::EVENT_REGISTER_DEFAULT_TABLE_ATTRIBUTES,
236
                [
237
                    RegisterOrganizationUserElementDefaultTableAttributes::class,
238
                    'handle'
239
                ]
240
            );
241
242
            // Add attributes the user index
243
            Event::off(
244
                User::class,
245
                User::EVENT_REGISTER_TABLE_ATTRIBUTES,
246
                [
247
                    RegisterOrganizationUserElementTableAttributes::class,
248
                    'handle'
249
                ]
250
            );
251
252
            // Add 'organizations' on the user html element
253
            Event::off(
254
                User::class,
255
                User::EVENT_SET_TABLE_ATTRIBUTE_HTML,
256
                [
257
                    SetOrganizationUserElementTableAttributeHtml::class,
258
                    'handle'
259
                ]
260
            );
261
        }
262
263
        return $this->asJson($response);
264
    }
265
266
    /**
267
     * @param null $user
268
     * @param null $organization
269
     * @return \yii\web\Response
270
     * @throws \Twig_Error_Loader
271
     * @throws \yii\base\Exception
272
     */
273
    public function actionAssociationEditorHtml($user = null, $organization = null)
274
    {
275
        if (null === $organization) {
276
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
277
        }
278
279
        if (null === $user) {
280
            $user = Craft::$app->getRequest()->getBodyParam(
281
                'user',
282
                Craft::$app->getRequest()->getBodyParam('elementId')
283
            );
284
        }
285
286
        $userAssociation = UserAssociation::findOne([
287
            'user' => $user,
288
            'organization' => $organization
289
        ]);
290
291
        $view = Craft::$app->getView();
292
        return $this->asJson([
293
            'html' => Craft::$app->getView()->renderTemplate(
294
                "organizations/_cp/_components/userAssociationEditorHtml",
295
                [
296
                    'association' => $userAssociation
297
                ]
298
            ),
299
            'headHtml' => $view->getHeadHtml(),
300
            'footHtml' => $view->getBodyHtml()
301
        ]);
302
    }
303
}
304