Completed
Push — master ( 5d951f...f67c03 )
by Nate
13:58 queued 11:06
created

OrganizationTypeSettings::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
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\services;
10
11
use Craft;
12
use craft\helpers\ArrayHelper;
13
use craft\queue\jobs\ResaveElements;
14
use flipbox\ember\services\traits\records\Accessor;
15
use flipbox\organizations\elements\Organization as OrganizationElement;
16
use flipbox\organizations\Organizations as OrganizationPlugin;
17
use flipbox\organizations\records\OrganizationType as TypeModel;
18
use flipbox\organizations\records\OrganizationTypeSiteSettings as TypeSettingsRecord;
19
use yii\base\Component;
20
21
/**
22
 * @author Flipbox Factory <[email protected]>
23
 * @since 1.0.0
24
 *
25
 * @method TypeSettingsRecord create(array $attributes = [])
26
 * @method TypeSettingsRecord find($identifier)
27
 * @method TypeSettingsRecord get($identifier)
28
 * @method TypeSettingsRecord findByCondition($condition = [])
29
 * @method TypeSettingsRecord getByCondition($condition = [])
30
 * @method TypeSettingsRecord findByCriteria($criteria = [])
31
 * @method TypeSettingsRecord getByCriteria($criteria = [])
32
 * @method TypeSettingsRecord[] findAllByCondition($condition = [])
33
 * @method TypeSettingsRecord[] getAllByCondition($condition = [])
34
 * @method TypeSettingsRecord[] findAllByCriteria($criteria = [])
35
 * @method TypeSettingsRecord[] getAllByCriteria($criteria = [])
36
 */
37
class OrganizationTypeSettings extends Component
38
{
39
    use Accessor;
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public function init()
45
    {
46
        $settings = OrganizationPlugin::getInstance()->getSettings();
47
        $this->cacheDuration = $settings->organizationTypeSettingsCacheDuration;
48
        $this->cacheDependency = $settings->organizationTypeSettingsCacheDependency;
49
50
        parent::init();
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public static function recordClass(): string
57
    {
58
        return TypeSettingsRecord::class;
59
    }
60
61
    /*******************************************
62
     * SAVE ALL BY TYPE
63
     *******************************************/
64
65
    /**
66
     * @param TypeModel $type
67
     * @return bool
68
     * @throws \Exception
69
     * @throws \Throwable
70
     * @throws \yii\db\StaleObjectException
71
     */
72
    public function saveByType(
73
        TypeModel $type
74
    ): bool {
75
        $successful = true;
76
77
        /** @var TypeSettingsRecord[] $allSettings */
78
        $allSettings = $type->hasMany(TypeSettingsRecord::class, ['typeId' => 'id'])
79
            ->indexBy('siteId')
80
            ->all();
81
82
        foreach ($type->getSiteSettings() as $model) {
83
            ArrayHelper::remove($allSettings, $model->siteId);
84
            $model->typeId = $type->getId();
85
86
            if (!$model->save()) {
87
                $successful = false;
88
                // Log the errors
89
                $error = Craft::t(
90
                    'organizations',
91
                    "Couldn't save site settings due to validation errors:"
92
                );
93
                foreach ($model->getFirstErrors() as $attributeError) {
94
                    $error .= "\n- " . Craft::t('organizations', $attributeError);
95
                }
96
97
                $type->addError('sites', $error);
98
            }
99
        }
100
101
        // Delete old settings records
102
        foreach ($allSettings as $settings) {
103
            $settings->delete();
104
            $this->reSaveOrganizations($settings);
105
        }
106
107
        return $successful;
108
    }
109
110
    /**
111
     * @param TypeSettingsRecord $type
112
     * @param bool $insert
113
     * @param array $changedAttributes
114
     */
115
    public function afterSave(TypeSettingsRecord $type, bool $insert, array $changedAttributes)
116
    {
117
        if ($insert === true) {
118
            return;
119
        }
120
121
        if (array_key_exists('uriFormat', $changedAttributes) ||
122
            (array_key_exists('hasUrls', $changedAttributes) &&
123
                $type->getOldAttribute('hasUrls') != $type->getAttribute('hasUrls'))
124
        ) {
125
            $this->reSaveOrganizations($type);
126
        }
127
    }
128
129
    /**
130
     * @param TypeSettingsRecord $type
131
     */
132
    private function reSaveOrganizations(TypeSettingsRecord $type)
133
    {
134
        Craft::$app->getQueue()->push(new ResaveElements([
135
            'description' => Craft::t('organizations', 'Re-saving organizations (Site: {site})', [
136
                'site' => $type->getSiteId(),
137
            ]),
138
            'elementType' => OrganizationElement::class,
139
            'criteria' => [
140
                'siteId' => $type->getSiteId(),
141
                'typeId' => $type->getTypeId(),
142
                'status' => null,
143
                'enabledForSite' => false,
144
            ]
145
        ]));
146
    }
147
}
148