Passed
Pull Request — master (#20)
by Jason
01:49
created

Setting::store_name_warning()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
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\Dev\Debug;
7
use SilverStripe\Forms\CheckboxField;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\FormAction;
10
use SilverStripe\Forms\LiteralField;
11
use SilverStripe\Forms\ReadonlyField;
12
use SilverStripe\Forms\TextField;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\ORM\DB;
15
use SilverStripe\ORM\ValidationException;
16
use SilverStripe\Security\Permission;
17
use SilverStripe\Security\PermissionProvider;
18
use SilverStripe\Security\Security;
19
use SilverStripe\View\TemplateGlobalProvider;
20
21
/**
22
 * Class Setting
23
 * @package Dynamic\Foxy\Model
24
 *
25
 * @property string $StoreKey
26
 * @property string $StoreTitle
27
 * @property string $StoreDomain
28
 */
29
class Setting extends DataObject implements PermissionProvider, TemplateGlobalProvider
30
{
31
    /**
32
     * @var string
33
     */
34
    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...
35
36
    /**
37
     * @var string
38
     */
39
    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...
40
41
    /**
42
     * @var string
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
     */
49
    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...
50
51
    /**
52
     * @var string
53
     */
54
    private static $keyPrefix = "dYnm1c";
0 ignored issues
show
introduced by
The private property $keyPrefix is not used, and could be removed.
Loading history...
55
56
    /**
57
     * @var array
58
     */
59
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
60
        'StoreKey' => 'Varchar(60)',
61
    ];
62
63
    /**
64
     * Default permission to check for 'LoggedInUsers' to create or edit pages.
65
     *
66
     * @var array
67
     * @config
68
     */
69
    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...
70
71
    /**
72
     * @return FieldList
73
     */
74
    public function getCMSFields()
75
    {
76
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
77
            $fields->removeByName([
78
                'StoreKey',
79
            ]);
80
81
            $fields->addFieldsToTab('Root.Main', [
82
                ReadonlyField::create('StoreDomain', 'Store Domain', FoxyHelper::config()->get('cart_url'))
83
                    ->setDescription('This is a unique FoxyCart subdomain for your cart, checkout, and receipt'),
84
                CheckboxField::create('CustomSSL', 'Use custom SSL', FoxyHelper::config()->get('custom_ssl'))
85
                    ->performReadonlyTransformation(),
86
            ]);
87
88
            if (FoxyHelper::config()->get('secret') != null) {
89
                $key = FoxyHelper::config()->get('secret');
90
                $description = 'Your secret key as set in config.yml';
91
            } else {
92
                $key = $this->StoreKey;
93
                $description = 'Recommended secret key for your Foxy store. Add to your config.yml to implement';
94
            }
95
96
            $fields->addFieldToTab(
97
                'Root.Main',
98
                ReadonlyField::create('Key', 'Store Key', $key)
99
                    ->setDescription($description)
100
            );
101
102
            if (self::store_name_warning() !== null) {
103
                $fields->addFieldToTab('Root.Main', LiteralField::create('StoreSubDomainHeaderWarning', _t(
104
                    'ProductPage.StoreSubDomainHeaderWarning',
105
                    '<p class="message error">Store domain must be entered in the 
106
                        <a href="/admin/foxy/">Foxy settings</a></p>'
107
                )), 'StoreDomain');
108
            }
109
        });
110
111
        return parent::getCMSFields();
112
    }
113
114
    /**
115
     * @return FieldList
116
     */
117
    public function getCMSActions()
118
    {
119
        if (Permission::check('ADMIN') || Permission::check('EDIT_FOXY_SETTING')) {
120
            $actions = new FieldList(
121
                FormAction::create('save_foxy_setting', _t(static::class . '.SAVE', 'Save'))
122
                    ->addExtraClass('btn-primary font-icon-save')
123
            );
124
        } else {
125
            $actions = FieldList::create();
126
        }
127
        $this->extend('updateCMSActions', $actions);
128
        return $actions;
129
    }
130
131
    /**
132
     * @return mixed|null
133
     * @throws \SilverStripe\ORM\ValidationException
134
     */
135
    public static function getStoreKey()
136
    {
137
        if ($storeKey = FoxyHelper::config()->get('StoreKey')) {
138
            return $storeKey;
139
        }
140
        return false;
141
    }
142
143
    /**
144
     * @return mixed|null
145
     * @throws \SilverStripe\ORM\ValidationException
146
     */
147
    public static function getStoreDomain()
148
    {
149
        if ($storeDomain = FoxyHelper::config()->get('cart_url')) {
150
            return $storeDomain;
151
        }
152
        return false;
153
    }
154
155
    /**
156
     * @return null|string
157
     * @throws \SilverStripe\ORM\ValidationException
158
     */
159
    // todo - move to Setting
160
    public static function store_name_warning()
161
    {
162
        $warning = null;
163
        if (!self::getStoreDomain()) {
164
            $warning = 'Must define FoxyCart Store Name or Store Remote Domain in your site settings in the cms';
165
        }
166
        return $warning;
167
    }
168
169
    /**
170
     *
171
     */
172
    public function requireDefaultRecords()
173
    {
174
        parent::requireDefaultRecords();
175
        if (!self::current_foxy_setting()) {
176
            self::make_foxy_setting();
177
            DB::alteration_message('Added default FoxyStripe Setting', 'created');
178
        }
179
    }
180
181
    /**
182
     *
183
     */
184
    public function onBeforeWrite()
185
    {
186
        parent::onBeforeWrite();
187
        if (!$this->StoreKey) {
188
            $key = $this->generateStoreKey();
189
            while (!ctype_alnum($key)) {
190
                $key = $this->generateStoreKey();
191
            }
192
            $this->StoreKey = $key;
193
            DB::alteration_message('Created FoxyCart Store Key ' . $key, 'created');
194
        }
195
    }
196
197
    /**
198
     * @param int $count
199
     * @return string
200
     */
201
    public function generateStoreKey($count = 0)
202
    {
203
        $length = $this->obj('StoreKey')->getSize() - strlen($this->config()->get('keyPrefix'));
204
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' . strtotime('now');
205
        $strLength = strlen($charset);
206
        $str = '';
207
208
        while ($count < $length) {
209
            $str .= $charset[mt_rand(0, $strLength - 1)];
210
            $count++;
211
        }
212
        return $this->config()->get('keyPrefix') . substr(base64_encode($str), 0, $length);
213
    }
214
215
    /**
216
     * @return string
217
     */
218
    public function CMSEditLink()
219
    {
220
        return FoxyAdmin::singleton()->Link();
221
    }
222
223
    /**
224
     * @param \SilverStripe\Security\Member|null $member
225
     *
226
     * @return bool|int|null
227
     */
228
    public function canEdit($member = null)
229
    {
230
        if (!$member) {
231
            $member = Security::getCurrentUser();
232
        }
233
        $extended = $this->extendedCan('canEdit', $member);
234
        if ($extended !== null) {
235
            return $extended;
236
        }
237
        return Permission::checkMember($member, 'EDIT_FOXY_SETTING');
238
    }
239
240
    /**
241
     * @return array
242
     */
243
    public function providePermissions()
244
    {
245
        return [
246
            'EDIT_FOXY_SETTING' => [
247
                'name' => _t(
248
                    static::class . '.EDIT_FOXY_SETTING',
249
                    'Manage FoxyStripe settings'
250
                ),
251
                'category' => _t(
252
                    static::class . '.PERMISSIONS_FOXY_SETTING',
253
                    'FoxyStripe'
254
                ),
255
                'help' => _t(
256
                    static::class . '.EDIT_PERMISSION_FOXY_SETTING',
257
                    'Ability to edit the settings of a FoxyStripe Store.'
258
                ),
259
                'sort' => 400,
260
            ],
261
        ];
262
    }
263
264
    /**
265
     * Get the current sites {@link GlobalSiteSetting}, and creates a new one
266
     * through {@link make_global_config()} if none is found.
267
     *
268
     * @return self|DataObject
269
     */
270
    public static function current_foxy_setting()
271
    {
272
        if ($config = self::get()->first()) {
273
            return $config;
274
        }
275
        return self::make_foxy_setting();
276
    }
277
278
    /**
279
     * Create {@link GlobalSiteSetting} with defaults from language file.
280
     *
281
     * @return self
282
     */
283
    public static function make_foxy_setting()
284
    {
285
        $config = self::create();
286
        try {
287
            $config->write();
288
        } catch (ValidationException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
289
        }
290
        return $config;
291
    }
292
293
    /**
294
     * Add $GlobalConfig to all SSViewers.
295
     *
296
     * @return array
297
     */
298
    public static function get_template_global_variables()
299
    {
300
        return [
301
            'FoxyStripe' => 'current_foxy_setting',
302
        ];
303
    }
304
}
305