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