Completed
Push — master ( e06ec5...c188b8 )
by Nate
12:22 queued 09:59
created

Organization::getIsEditable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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\OrganizationType 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
     * @inheritdoc
37
     */
38
    public static function displayName(): string
39
    {
40
        return Craft::t('organizations', 'Organization');
41
    }
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function getIsEditable(): bool
47
    {
48
        return true;
49
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54
    public static function hasTitles(): bool
55
    {
56
        return true;
57
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62
    public static function isLocalized(): bool
63
    {
64
        return true;
65
    }
66
67
    /**
68
     * @inheritdoc
69
     */
70
    public static function hasContent(): bool
71
    {
72
        return true;
73
    }
74
75
    /**
76
     * @inheritdoc
77
     */
78
    public static function hasUris(): bool
79
    {
80
        return true;
81
    }
82
83
    /**
84
     * @inheritdoc
85
     *
86
     * @return OrganizationQuery
87
     */
88
    public static function find(): ElementQueryInterface
89
    {
90
        return new OrganizationQuery(static::class);
91
    }
92
93
    /**
94
     * Returns whether this element type can have statuses.
95
     *
96
     * @return boolean
97
     */
98
    public static function hasStatuses(): bool
99
    {
100
        return true;
101
    }
102
103
    /**
104
     * @inheritdoc
105
     */
106
    public function getRef()
107
    {
108
        if (!$primary = $this->getPrimaryType()) {
109
            return $this->slug;
110
        }
111
112
        return $primary->handle . '/' . $this->slug;
113
    }
114
115
    /**
116
     * @return array
117
     */
118
    public function attributes()
119
    {
120
        return array_merge(
121
            parent::attributes(),
122
            $this->dateJoinedAttributes(),
123
            [
124
                //                'types',
125
                //                'activeType',
126
                //                'primaryType',
127
                //                'users',
128
            ]
129
        );
130
    }
131
132
    /**
133
     * @inheritdoc
134
     */
135
    public function rules()
136
    {
137
        return array_merge(
138
            parent::rules(),
139
            $this->dateJoinedRules(),
140
            [
141
                [
142
                    [
143
                        'types',
144
                        'activeType',
145
                        'primaryType',
146
                        'users',
147
                    ],
148
                    'safe',
149
                    'on' => [
150
                        ModelHelper::SCENARIO_DEFAULT
151
                    ]
152
153
                ],
154
            ]
155
        );
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    public function attributeLabels()
162
    {
163
        return array_merge(
164
            parent::attributeLabels(),
165
            $this->dateJoinedAttributeLabels(),
166
            [
167
                //                'types' => Craft::t('organizations', 'Types'),
168
                //                'activeType' => Craft::t('organizations', 'Active Type'),
169
                //                'primaryType' => Craft::t('organizations', 'Primary Type'),
170
                //                'users' => Craft::t('organizations', 'Users'),
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('organizations', '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()->getOrganizationTypes()->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('organizations', '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
        ];
314
    }
315
316
    /**
317
     * @inheritdoc
318
     */
319
    protected static function defineSortOptions(): array
320
    {
321
        return [
322
            'title' => Craft::t('organizations', 'Name'),
323
            'dateJoined' => Craft::t('organizations', 'Join Date'),
324
        ];
325
    }
326
327
    /**
328
     * @inheritdoc
329
     */
330
    public static function eagerLoadingMap(array $sourceElements, string $handle)
331
    {
332
        switch ($handle) {
333
            case 'users':
334
                return self::eagerLoadingUsersMap($sourceElements);
335
        }
336
337
        return parent::eagerLoadingMap($sourceElements, $handle);
338
    }
339
340
    /**
341
     * @inheritdoc
342
     */
343
    public function setEagerLoadedElements(string $handle, array $elements)
344
    {
345
        switch ($handle) {
346
            case 'users':
347
                $users = $elements ?? [];
348
                $this->setUsers($users);
349
                break;
350
351
            default:
352
                parent::setEagerLoadedElements($handle, $elements);
353
        }
354
    }
355
356
    /**
357
     * @inheritdoc
358
     */
359
    public static function defineTableAttributes(): array
360
    {
361
        return [
362
            'id' => ['label' => Craft::t('app', 'Name')],
363
            'uri' => ['label' => Craft::t('app', 'URI')],
364
            'types' => ['label' => Craft::t('organizations', 'Type(s)')],
365
            'dateJoined' => ['label' => Craft::t('organizations', 'Join Date')],
366
            'dateCreated' => ['label' => Craft::t('app', 'Date Created')],
367
            'dateUpdated' => ['label' => Craft::t('app', 'Date Updated')],
368
        ];
369
    }
370
371
372
373
    // Indexes, etc.
374
    // -------------------------------------------------------------------------
375
376
    /**
377
     * @inheritdoc
378
     */
379
    public function tableAttributeHtml(string $attribute): string
380
    {
381
382
        switch ($attribute) {
383
            case 'types':
384
                $typeHtmlParts = [];
385
                foreach ($this->getTypes()->all() as $type) {
386
                    $typeHtmlParts[] = '<a href="' .
387
                        UrlHelper::cpUrl('organizations/' . $this->id . '/' . $type->handle) .
388
                        '">' .
389
                        $type->name .
390
                        '</a>';
391
                }
392
393
                return !empty($typeHtmlParts) ? StringHelper::toString($typeHtmlParts, ', ') : '';
394
        }
395
396
        return parent::tableAttributeHtml($attribute);
397
    }
398
399
    /**
400
     * @inheritdoc
401
     */
402
    public function getUriFormat()
403
    {
404
        return OrganizationPlugin::getInstance()->getElement()->getUriFormat($this);
405
    }
406
407
    /**
408
     * @inheritdoc
409
     */
410
    public function route()
411
    {
412
        return OrganizationPlugin::getInstance()->getElement()->getRoute($this);
413
    }
414
415
    /************************************************************
416
     * EVENTS
417
     ************************************************************/
418
419
    /**
420
     * @inheritdoc
421
     * @throws Exception
422
     */
423
    public function beforeSave(bool $isNew): bool
424
    {
425
        OrganizationPlugin::getInstance()->getElement()->beforeSave($this);
426
        return parent::beforeSave($isNew);
427
    }
428
429
    /**
430
     * @inheritdoc
431
     * @throws Exception
432
     */
433
    public function afterSave(bool $isNew)
434
    {
435
        OrganizationPlugin::getInstance()->getElement()->afterSave($this, $isNew);
436
        parent::afterSave($isNew);
437
    }
438
}
439