Passed
Pull Request — master (#12)
by Matthew
01:31
created

Setting::make_foxy_setting()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dynamic\Foxy\Model;
4
5
use Dynamic\Foxy\Admin\FoxyAdmin;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\Forms\FormAction;
8
use SilverStripe\Forms\ReadonlyField;
9
use SilverStripe\Forms\TextField;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\DB;
12
use SilverStripe\ORM\ValidationException;
13
use SilverStripe\Security\Permission;
14
use SilverStripe\Security\PermissionProvider;
15
use SilverStripe\Security\Security;
16
use SilverStripe\View\TemplateGlobalProvider;
17
18
/**
19
 * Class Setting
20
 * @package Dynamic\Foxy\Model
21
 *
22
 * @property string $StoreKey
23
 * @property string $StoreTitle
24
 * @property string $StoreDomain
25
 */
26
class Setting extends DataObject implements PermissionProvider, TemplateGlobalProvider
27
{
28
    /**
29
     * @var string
30
     * @scrutinizer ignore-unused
31
     */
32
    private static $singular_name = 'Foxy Setting';
0 ignored issues
show
introduced by
The private property $singular_name is not used, and could be removed.
Loading history...
33
34
    /**
35
     * @var string
36
     * @scrutinizer ignore-unused
37
     */
38
    private static $plural_name = 'Foxy Settings';
0 ignored issues
show
introduced by
The private property $plural_name is not used, and could be removed.
Loading history...
39
40
    /**
41
     * @var string
42
     * @scrutinizer ignore-unused
43
     */
44
    private static $description = 'Update the settings for your store';
0 ignored issues
show
introduced by
The private property $description is not used, and could be removed.
Loading history...
45
46
    /**
47
     * @var string
48
     * @scrutinizer ignore-unused
49
     */
50
    private static $table_name = 'FoxySetting';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
51
52
    /**
53
     * @var string
54
     * @scrutinizer ignore-unused
55
     */
56
    private static $keyPrefix = "dYnm1c";
0 ignored issues
show
introduced by
The private property $keyPrefix is not used, and could be removed.
Loading history...
57
58
    /**
59
     * @var array
60
     * @scrutinizer ignore-unused
61
     */
62
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
63
        'StoreKey' => 'Varchar(60)',
64
        'StoreTitle' => 'Varchar(255)',
65
        'StoreDomain' => 'Varchar(255)',
66
        // TODO
67
    ];
68
69
    /**
70
     * Default permission to check for 'LoggedInUsers' to create or edit pages.
71
     *
72
     * @var array
73
     * @config
74
     * @scrutinizer ignore-unused
75
     */
76
    private static $required_permission = ['CMS_ACCESS_CMSMain', 'CMS_ACCESS_LeftAndMain'];
0 ignored issues
show
introduced by
The private property $required_permission is not used, and could be removed.
Loading history...
77
78
    /**
79
     * @return FieldList
80
     */
81
    public function getCMSFields()
82
    {
83
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
84
            // TODO
85
            $fields->addFieldsToTab('Root.Main', [
86
                TextField::create('StoreTitle', 'Store Title')
87
                    ->setDescription('The name of your store as you\'d like it displayed to your customers'),
88
                TextField::create('StoreDomain', 'Store Domain')
89
                    ->setDescription('This is a unique FoxyCart subdomain for your cart, checkout, and receipt'),
90
            ]);
91
92
            $fields->addFieldsToTab('Root.Advanced', [
93
                ReadonlyField::create('StoreKey', 'Store Key', $this->StoreKey),
94
            ]);
95
        });
96
97
        return parent::getCMSFields();
98
    }
99
100
    /**
101
     * @return FieldList
102
     */
103
    public function getCMSActions()
104
    {
105
        if (Permission::check('ADMIN') || Permission::check('EDIT_FOXY_SETTING')) {
106
            $actions = new FieldList(
107
                FormAction::create('save_foxy_setting', _t(static::class . '.SAVE', 'Save'))
108
                    ->addExtraClass('btn-primary font-icon-save')
109
            );
110
        } else {
111
            $actions = FieldList::create();
112
        }
113
        $this->extend('updateCMSActions', $actions);
114
        return $actions;
115
    }
116
117
    /**
118
     *
119
     */
120
    public function requireDefaultRecords()
121
    {
122
        parent::requireDefaultRecords();
123
        if (!self::current_foxy_setting()) {
124
            self::make_foxy_setting();
125
            DB::alteration_message('Added default FoxyStripe Setting', 'created');
126
        }
127
    }
128
129
    /**
130
     *
131
     */
132
    public function onBeforeWrite()
133
    {
134
        parent::onBeforeWrite();
135
        if (!$this->StoreKey) {
136
            $key = $this->generateStoreKey();
137
            while (!ctype_alnum($key)) {
138
                $key = $this->generateStoreKey();
139
            }
140
            $this->StoreKey = $key;
141
            DB::alteration_message('Created FoxyCart Store Key ' . $key, 'created');
142
        }
143
    }
144
145
    /**
146
     * @param int $count
147
     * @return string
148
     */
149
    public function generateStoreKey($count = 0)
150
    {
151
        $length = $this->obj('StoreKey')->getSize() - strlen($this->config()->get('keyPrefix'));
152
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' . strtotime('now');
153
        $strLength = strlen($charset);
154
        $str = '';
155
156
        while ($count < $length) {
157
            $str .= $charset[mt_rand(0, $strLength - 1)];
158
            $count++;
159
        }
160
        return $this->config()->get('keyPrefix') . substr(base64_encode($str), 0, $length);
161
    }
162
163
    /**
164
     * @return string
165
     */
166
    public function CMSEditLink()
167
    {
168
        return FoxyAdmin::singleton()->Link();
169
    }
170
171
    /**
172
     * @param \SilverStripe\Security\Member|null $member
173
     *
174
     * @return bool|int|null
175
     */
176
    public function canEdit($member = null)
177
    {
178
        if (!$member) {
179
            $member = Security::getCurrentUser();
180
        }
181
        $extended = $this->extendedCan('canEdit', $member);
182
        if ($extended !== null) {
183
            return $extended;
184
        }
185
        return Permission::checkMember($member, 'EDIT_FOXY_SETTING');
186
    }
187
188
    /**
189
     * @return array
190
     */
191
    public function providePermissions()
192
    {
193
        return [
194
            'EDIT_FOXY_SETTING' => [
195
                'name' => _t(
196
                    static::class . '.EDIT_FOXY_SETTING',
197
                    'Manage FoxyStripe settings'
198
                ),
199
                'category' => _t(
200
                    static::class . '.PERMISSIONS_FOXY_SETTING',
201
                    'FoxyStripe'
202
                ),
203
                'help' => _t(
204
                    static::class . '.EDIT_PERMISSION_FOXY_SETTING',
205
                    'Ability to edit the settings of a FoxyStripe Store.'
206
                ),
207
                'sort' => 400,
208
            ],
209
        ];
210
    }
211
212
    /**
213
     * Get the current sites {@link GlobalSiteSetting}, and creates a new one
214
     * through {@link make_global_config()} if none is found.
215
     *
216
     * @return self|DataObject
217
     */
218
    public static function current_foxy_setting()
219
    {
220
        if ($config = self::get()->first()) {
221
            return $config;
222
        }
223
        return self::make_foxy_setting();
224
    }
225
226
    /**
227
     * Create {@link GlobalSiteSetting} with defaults from language file.
228
     *
229
     * @return self
230
     */
231
    public static function make_foxy_setting()
232
    {
233
        $config = self::create();
234
        try {
235
            $config->write();
236
        } catch (ValidationException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
237
        }
238
        return $config;
239
    }
240
241
    /**
242
     * Add $GlobalConfig to all SSViewers.
243
     *
244
     * @return array
245
     */
246
    public static function get_template_global_variables()
247
    {
248
        return [
249
            'FoxyStripe' => 'current_foxy_setting',
250
        ];
251
    }
252
}
253