Completed
Push — master ( 829e7b...9495f2 )
by Nate
01:24
created

src/cp/controllers/UsersController.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\UserTypesAssociatedToUserBehavior;
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 \yii\base\Exception
139
     */
140
    public function actionSaveAssociation($user = null, $organization = null)
141
    {
142
        if (null === $organization) {
143
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
144
        }
145
146
        if (null === $user) {
147
            $user = Craft::$app->getRequest()->getBodyParam(
148
                'user',
149
                Craft::$app->getRequest()->getBodyParam('elementId')
150
            );
151
        }
152
153
        $userAssociation = UserAssociation::findOne([
154
            'user' => $user,
155
            'organization' => $organization
156
        ]);
157
158
        $success = true;
159
160
        $userAssociation->state = Craft::$app->getRequest()->getBodyParam('state', $userAssociation->state);
161
162
        if (!$userAssociation->save(true, ['state'])) {
163
            $success = false;
164
        }
165
166
        $user = $userAssociation->getUser();
167
168
        if (null !== ($types = Craft::$app->getRequest()->getBodyParam('types'))) {
169
            $types = array_filter($types);
170
            $query = UserType::find()->id(empty($types) ? ':empty:' : $types);
171
172
            /** @var UserTypesAssociatedToUserBehavior|User $user */
173
            if (!$user->getUserTypeManager($userAssociation->getOrganization())
0 ignored issues
show
The method getUserTypeManager does only exist in flipbox\organizations\be...ssociatedToUserBehavior, 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...
174
                ->setMany($query)
175
                ->save()
176
            ) {
177
                $success = false;
178
                $userAssociation->addError('types', 'Unable to save types.');
179
            }
180
        }
181
182
        $response = [
183
            'success' => $success,
184
            'id' => $user->getId(),
185
            'newTitle' => (string)$user,
186
            'cpEditUrl' => $user->getCpEditUrl(),
187
        ];
188
189
        // Should we be including table attributes too?
190
        $sourceKey = Craft::$app->getRequest()->getBodyParam('includeTableAttributesForSource');
191
192
        if ($sourceKey) {
193
            Event::on(
194
                User::class,
195
                User::EVENT_REGISTER_DEFAULT_TABLE_ATTRIBUTES,
196
                [
197
                    RegisterOrganizationUserElementDefaultTableAttributes::class,
198
                    'handle'
199
                ]
200
            );
201
202
            // Add attributes the user index
203
            Event::on(
204
                User::class,
205
                User::EVENT_REGISTER_TABLE_ATTRIBUTES,
206
                [
207
                    RegisterOrganizationUserElementTableAttributes::class,
208
                    'handle'
209
                ]
210
            );
211
212
            // Add 'organizations' on the user html element
213
            Event::on(
214
                User::class,
215
                User::EVENT_SET_TABLE_ATTRIBUTE_HTML,
216
                [
217
                    SetOrganizationUserElementTableAttributeHtml::class,
218
                    'handle'
219
                ]
220
            );
221
222
            $attributes = Craft::$app->getElementIndexes()->getTableAttributes(get_class($user), $sourceKey);
223
224
            // Drop the first one
225
            array_shift($attributes);
226
227
            foreach ($attributes as $attribute) {
228
                $response['tableAttributes'][$attribute[0]] = $user->getTableAttributeHtml($attribute[0]);
229
            }
230
231
            Event::off(
232
                User::class,
233
                User::EVENT_REGISTER_DEFAULT_TABLE_ATTRIBUTES,
234
                [
235
                    RegisterOrganizationUserElementDefaultTableAttributes::class,
236
                    'handle'
237
                ]
238
            );
239
240
            // Add attributes the user index
241
            Event::off(
242
                User::class,
243
                User::EVENT_REGISTER_TABLE_ATTRIBUTES,
244
                [
245
                    RegisterOrganizationUserElementTableAttributes::class,
246
                    'handle'
247
                ]
248
            );
249
250
            // Add 'organizations' on the user html element
251
            Event::off(
252
                User::class,
253
                User::EVENT_SET_TABLE_ATTRIBUTE_HTML,
254
                [
255
                    SetOrganizationUserElementTableAttributeHtml::class,
256
                    'handle'
257
                ]
258
            );
259
        }
260
261
        return $this->asJson($response);
262
    }
263
264
    /**
265
     * @param null $user
266
     * @param null $organization
267
     * @return \yii\web\Response
268
     * @throws \Twig\Error\LoaderError
269
     * @throws \Twig\Error\RuntimeError
270
     * @throws \Twig\Error\SyntaxError
271
     */
272
    public function actionAssociationEditorHtml($user = null, $organization = null)
273
    {
274
        if (null === $organization) {
275
            $organization = Craft::$app->getRequest()->getBodyParam('organization');
276
        }
277
278
        if (null === $user) {
279
            $user = Craft::$app->getRequest()->getBodyParam(
280
                'user',
281
                Craft::$app->getRequest()->getBodyParam('elementId')
282
            );
283
        }
284
285
        $userAssociation = UserAssociation::findOne([
286
            'user' => $user,
287
            'organization' => $organization
288
        ]);
289
290
        $view = Craft::$app->getView();
291
        return $this->asJson([
292
            'html' => Craft::$app->getView()->renderTemplate(
293
                "organizations/_cp/_components/userAssociationEditorHtml",
294
                [
295
                    'association' => $userAssociation
296
                ]
297
            ),
298
            'headHtml' => $view->getHeadHtml(),
299
            'footHtml' => $view->getBodyHtml()
300
        ]);
301
    }
302
}
303