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

Setting::generateStoreKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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