Completed
Push — master ( 6f2475...9a35ef )
by Nate
16:01
created

Organization   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 413
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 38
lcom 3
cbo 11
dl 0
loc 413
ccs 0
cts 230
cp 0
rs 8.3999
c 0
b 0
f 0

28 Methods

Rating   Name   Duplication   Size   Complexity  
A displayName() 0 4 1
A hasTitles() 0 4 1
A isLocalized() 0 4 1
A hasContent() 0 4 1
A hasUris() 0 4 1
A find() 0 4 1
A hasStatuses() 0 4 1
A getRef() 0 8 2
A attributes() 0 14 1
A rules() 0 23 1
A attributeLabels() 0 14 1
A getFieldLayout() 0 8 2
A getCpEditUrl() 0 4 1
A defineSources() 0 10 2
A defineDefaultSources() 0 11 1
A defineTypeSources() 0 21 2
B defineUserSources() 0 24 2
A defineActions() 0 17 1
A defineSearchableAttributes() 0 7 1
A defineSortOptions() 0 8 1
A eagerLoadingMap() 0 9 2
A setEagerLoadedElements() 0 12 2
A defineTableAttributes() 0 12 1
A tableAttributeHtml() 0 19 4
A getUriFormat() 0 4 1
A route() 0 4 1
A beforeSave() 0 5 1
A afterSave() 0 5 1
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\elements;
10
11
use Craft;
12
use craft\base\Element;
13
use craft\elements\actions\Edit as EditAction;
14
use craft\elements\db\ElementQueryInterface;
15
use craft\elements\User;
16
use craft\helpers\StringHelper;
17
use craft\helpers\UrlHelper as UrlHelper;
18
use flipbox\ember\helpers\ModelHelper;
19
use flipbox\organizations\db\OrganizationQuery;
20
use flipbox\organizations\Organizations as OrganizationPlugin;
21
use flipbox\organizations\records\Type as TypeModel;
22
use flipbox\organizations\traits\DateJoinedAttribute;
23
use yii\base\ErrorException as Exception;
24
25
/**
26
 * @author Flipbox Factory <[email protected]>
27
 * @since 1.0.0
28
 */
29
class Organization extends Element
30
{
31
    use DateJoinedAttribute,
32
        traits\TypesAttribute,
33
        traits\UsersAttribute;
34
35
    /**
36
     * @var string
37
     */
38
    public $state;
39
40
    /**
41
     * @inheritdoc
42
     */
43
    public static function displayName(): string
44
    {
45
        return Craft::t('organizations', 'Organization');
46
    }
47
48
    /**
49
     * @inheritdoc
50
     */
51
    public static function hasTitles(): bool
52
    {
53
        return true;
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public static function isLocalized(): bool
60
    {
61
        return true;
62
    }
63
64
    /**
65
     * @inheritdoc
66
     */
67
    public static function hasContent(): bool
68
    {
69
        return true;
70
    }
71
72
    /**
73
     * @inheritdoc
74
     */
75
    public static function hasUris(): bool
76
    {
77
        return true;
78
    }
79
80
    /**
81
     * @inheritdoc
82
     *
83
     * @return OrganizationQuery
84
     */
85
    public static function find(): ElementQueryInterface
86
    {
87
        return new OrganizationQuery(static::class);
88
    }
89
90
    /**
91
     * Returns whether this element type can have statuses.
92
     *
93
     * @return boolean
94
     */
95
    public static function hasStatuses(): bool
96
    {
97
        return true;
98
    }
99
100
    /**
101
     * @inheritdoc
102
     */
103
    public function getRef()
104
    {
105
        if (!$primary = $this->getPrimaryType()) {
106
            return $this->slug;
107
        }
108
109
        return $primary->handle . '/' . $this->slug;
110
    }
111
112
    /**
113
     * @return array
114
     */
115
    public function attributes()
116
    {
117
        return array_merge(
118
            parent::attributes(),
119
            $this->dateJoinedAttributes(),
120
            [
121
                'state',
122
                //                'types',
123
                //                'activeType',
124
                //                'primaryType',
125
                //                'users',
126
            ]
127
        );
128
    }
129
130
    /**
131
     * @inheritdoc
132
     */
133
    public function rules()
134
    {
135
        return array_merge(
136
            parent::rules(),
137
            $this->dateJoinedRules(),
138
            [
139
                [
140
                    [
141
                        'types',
142
                        'activeType',
143
                        'primaryType',
144
                        'users',
145
                        'state'
146
                    ],
147
                    'safe',
148
                    'on' => [
149
                        ModelHelper::SCENARIO_DEFAULT
150
                    ]
151
152
                ],
153
            ]
154
        );
155
    }
156
157
    /**
158
     * @return array
159
     */
160
    public function attributeLabels()
161
    {
162
        return array_merge(
163
            parent::attributeLabels(),
164
            $this->dateJoinedAttributeLabels(),
165
            [
166
                //                'types' => Craft::t('organizations', 'Types'),
167
                //                'activeType' => Craft::t('organizations', 'Active Type'),
168
                //                'primaryType' => Craft::t('organizations', 'Primary Type'),
169
                //                'users' => Craft::t('organizations', 'Users'),
170
                'state' => Craft::t('organizations', 'State')
171
            ]
172
        );
173
    }
174
175
    /************************************************************
176
     * FIELD LAYOUT
177
     ************************************************************/
178
179
    /**
180
     * @inheritdoc
181
     */
182
    public function getFieldLayout()
183
    {
184
        if (!$type = $this->getActiveType()) {
185
            return OrganizationPlugin::getInstance()->getSettings()->getFieldLayout();
186
        }
187
188
        return $type->getFieldLayout();
189
    }
190
191
    /************************************************************
192
     * ELEMENT ADMIN
193
     ************************************************************/
194
195
    /**
196
     * @inheritdoc
197
     */
198
    public function getCpEditUrl()
199
    {
200
        return UrlHelper::cpUrl('organizations/' . $this->id);
201
    }
202
203
    /**
204
     * @inheritdoc
205
     */
206
    protected static function defineSources(string $context = null): array
207
    {
208
        switch ($context) {
209
            case 'user':
210
                return self::defineUserSources();
211
212
            default:
213
                return self::defineTypeSources();
214
        }
215
    }
216
217
    /**
218
     * @return array
219
     */
220
    private static function defineDefaultSources(): array
221
    {
222
        return [
223
            [
224
                'key' => '*',
225
                'label' => Craft::t('app', 'All organizations'),
226
                'criteria' => ['status' => null],
227
                'hasThumbs' => true
228
            ]
229
        ];
230
    }
231
232
    /**
233
     * @return array
234
     */
235
    private static function defineTypeSources(): array
236
    {
237
        $sources = self::defineDefaultSources();
238
239
        // Array of all organization types
240
        $organizationTypes = OrganizationPlugin::getInstance()->getTypes()->findAll();
241
242
        $sources[] = ['heading' => Craft::t('organizations', 'Types')];
243
244
        /** @var TypeModel $organizationType */
245
        foreach ($organizationTypes as $organizationType) {
246
            $sources[] = [
247
                'key' => 'type:' . $organizationType->id,
248
                'label' => $organizationType->name,
249
                'criteria' => ['status' => null, 'typeId' => $organizationType->id],
250
                'hasThumbs' => true
251
            ];
252
        }
253
254
        return $sources;
255
    }
256
257
    /**
258
     * @return array
259
     */
260
    private static function defineUserSources(): array
261
    {
262
        $sources = self::defineDefaultSources();
263
264
        // Array of all organization types
265
        $organizationUsers = OrganizationPlugin::getInstance()->getUsers()->getQuery();
266
267
        $sources[] = ['heading' => Craft::t('organizations', 'Users')];
268
269
        /** @var User $organizationUser */
270
        foreach ($organizationUsers as $organizationUser) {
271
            $sources[] = [
272
                'key' => 'user:' . $organizationUser->id,
273
                'label' => $organizationUser->getFullName(),
274
                'criteria' => [
275
                    'status' => null,
276
                    'users' => [$organizationUser->id]
277
                ],
278
                'hasThumbs' => true
279
            ];
280
        }
281
282
        return $sources;
283
    }
284
285
    /**
286
     * @inheritdoc
287
     */
288
    protected static function defineActions(string $source = null): array
289
    {
290
        $actions = [];
291
292
        // Edit
293
        $actions[] = Craft::$app->getElements()->createAction([
294
            'type' => EditAction::class,
295
            'label' => Craft::t('app', 'Edit organization'),
296
        ]);
297
298
//        if (Craft::$app->getUser()->checkPermission('deleteOrganizations')) {
299
//            // Delete
300
//            $actions[] = DeleteAction::class;
301
//        }
302
303
        return $actions;
304
    }
305
306
    /**
307
     * @inheritdoc
308
     */
309
    protected static function defineSearchableAttributes(): array
310
    {
311
        return [
312
            'id',
313
            'state'
314
        ];
315
    }
316
317
    /**
318
     * @inheritdoc
319
     */
320
    protected static function defineSortOptions(): array
321
    {
322
        return [
323
            'title' => Craft::t('organizations', 'Name'),
324
            'dateJoined' => Craft::t('organizations', 'Join Date'),
325
            'state' => Craft::t('organizations', 'Status')
326
        ];
327
    }
328
329
    /**
330
     * @inheritdoc
331
     */
332
    public static function eagerLoadingMap(array $sourceElements, string $handle)
333
    {
334
        switch ($handle) {
335
            case 'users':
336
                return self::eagerLoadingUsersMap($sourceElements);
337
        }
338
339
        return parent::eagerLoadingMap($sourceElements, $handle);
340
    }
341
342
    /**
343
     * @inheritdoc
344
     */
345
    public function setEagerLoadedElements(string $handle, array $elements)
346
    {
347
        switch ($handle) {
348
            case 'users':
349
                $users = $elements ?? [];
350
                $this->setUsers($users);
351
                break;
352
353
            default:
354
                parent::setEagerLoadedElements($handle, $elements);
355
        }
356
    }
357
358
    /**
359
     * @inheritdoc
360
     */
361
    public static function defineTableAttributes(): array
362
    {
363
        return [
364
            'id' => ['label' => Craft::t('app', 'Name')],
365
            'uri' => ['label' => Craft::t('app', 'URI')],
366
            'state' => ['label' => Craft::t('organizations', 'State')],
367
            'types' => ['label' => Craft::t('organizations', 'Type(s)')],
368
            'dateJoined' => ['label' => Craft::t('organizations', 'Join Date')],
369
            'dateCreated' => ['label' => Craft::t('app', 'Date Created')],
370
            'dateUpdated' => ['label' => Craft::t('app', 'Date Updated')],
371
        ];
372
    }
373
374
375
376
    // Indexes, etc.
377
    // -------------------------------------------------------------------------
378
379
    /**
380
     * @inheritdoc
381
     */
382
    public function tableAttributeHtml(string $attribute): string
383
    {
384
385
        switch ($attribute) {
386
            case 'types':
387
                $typeHtmlParts = [];
388
                foreach ($this->getTypes()->all() as $type) {
389
                    $typeHtmlParts[] = '<a href="' .
390
                        UrlHelper::cpUrl('/organization/' . $this->id . '/' . $type->handle) .
391
                        '">' .
392
                        $type->name .
393
                        '</a>';
394
                }
395
396
                return !empty($typeHtmlParts) ? StringHelper::toString($typeHtmlParts, ', ') : '';
397
        }
398
399
        return parent::tableAttributeHtml($attribute);
400
    }
401
402
    /**
403
     * @inheritdoc
404
     */
405
    public function getUriFormat()
406
    {
407
        return OrganizationPlugin::getInstance()->getElement()->getUriFormat($this);
408
    }
409
410
    /**
411
     * @inheritdoc
412
     */
413
    public function route()
414
    {
415
        return OrganizationPlugin::getInstance()->getElement()->getRoute($this);
416
    }
417
418
    /************************************************************
419
     * EVENTS
420
     ************************************************************/
421
422
    /**
423
     * @inheritdoc
424
     * @throws Exception
425
     */
426
    public function beforeSave(bool $isNew): bool
427
    {
428
        OrganizationPlugin::getInstance()->getElement()->beforeSave($this);
429
        return parent::beforeSave($isNew);
430
    }
431
432
    /**
433
     * @inheritdoc
434
     * @throws Exception
435
     */
436
    public function afterSave(bool $isNew)
437
    {
438
        OrganizationPlugin::getInstance()->getElement()->afterSave($this, $isNew);
439
        parent::afterSave($isNew);
440
    }
441
}
442