ThreemaGateway_Option_Status::renderHtml()   B
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 56
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 8.7592
c 0
b 0
f 0
cc 5
eloc 29
nc 9
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Status managment for Threema Gateway.
4
 *
5
 * @package ThreemaGateway
6
 * @author rugk
7
 * @copyright Copyright (c) 2015-2016 rugk
8
 * @license MIT
9
 */
10
11
class ThreemaGateway_Option_Status
12
{
13
    /**
14
     * @var int Below this amount of credits a warning is shown.
15
     */
16
    const CREDITS_WARN = 100;
17
18
    /**
19
     * Renders the status "option".
20
     *
21
     * @param XenForo_View $view           View object
22
     * @param string       $fieldPrefix    Prefix for the HTML form field name
23
     * @param array        $preparedOption Prepared option info
24
     * @param bool         $canEdit        True if an "edit" link should appear
25
     *
26
     * @return XenForo_Template_Abstract Template object
27
     */
28
    public static function renderHtml(XenForo_View $view, $fieldPrefix, array $preparedOption, $canEdit)
29
    {
30
        /** @var array $status */
31
        $status = ['libsodium', 'libsodiumphp', 'phpsdk', 'credits'];
32
        /** @var array $extraError */
33
        $extraError = [];
34
35
        /** @var bool $technSuccess */
36
        $technSuccess = self::checkTecRequire($status, $extraError);
37
38
        /** @var ThreemaGateway_Handler_Settings $gwSettings */
39
        $gwSettings = new ThreemaGateway_Handler_Settings;
40
41
        // only go on if technically everything is okay to prevent PHP errors when accessing the SDK
42
        if ($technSuccess) {
43
            /** @var bool $phpSdkSuccess */
44
            $phpSdkSuccess = self::checkPhpSdk($status, $extraError, $gwSettings);
45
46
            // Only continue if there are no errors in the PHP SDK.
47
            // We could try it anyway, but this would be useless as it certainly
48
            // fails anyway and if you have a broken setup, you also have bigger
49
            // issues than your credits count.
50
            if ($phpSdkSuccess) {
51
                self::queryCredits($status, $extraError);
52
            }
53
        }
54
55
        if ($gwSettings->isDebug()) {
56
            if (XenForo_Application::debugMode()) {
57
                $extraError[] = [
58
                    'text' => new XenForo_Phrase('option_threema_gateway_status_debug_mode_active'),
59
                    'descclass' => 'warning'
60
                ];
61
            } else {
62
                $extraError[] = [
63
                    'text' => new XenForo_Phrase('option_threema_gateway_status_debug_mode_potentially_active'),
64
                    'descclass' => 'warning'
65
                ];
66
            }
67
        }
68
69
        $editLink = $view->createTemplateObject('option_list_option_editlink', [
70
            'preparedOption' => $preparedOption,
71
            'canEditOptionDefinition' => $canEdit
72
        ]);
73
74
        return $view->createTemplateObject('threemagw_option_list_status', [
75
            'fieldPrefix' => $fieldPrefix,
76
            'listedFieldName' => $fieldPrefix . '_listed[]',
77
            'preparedOption' => $preparedOption,
78
            'editLink' => $editLink,
79
            'status' => $status,
80
            'extraError' => $extraError,
81
            'technSuccess' => $technSuccess
82
        ]);
83
    }
84
85
    /**
86
     * Checks whether all technical requirements of the add-on installation
87
     * are fullfilled.
88
     *
89
     * Mostly only checks for Libsodium and Libsodium-PHP.
90
     * Return false when a serious error happens, which indicates that the
91
     * requirements are not fullfilled.
92
     *
93
     * @param  array $status     Will be filled with required statuses (sic)
94
     * @param  array $extraError Optional other errors may be added here
95
     * @return bool
96
     */
97
    protected static function checkTecRequire(array &$status, array &$extraError)
98
    {
99
        // optional check: HTTPS
100
        if (!XenForo_Application::$secure) {
101
            $extraError[]['text'] = new XenForo_Phrase('option_threema_gateway_status_no_https');
102
        }
103
104
        //libsodium
105
        if (extension_loaded('libsodium')) {
106
            if (method_exists('Sodium', 'sodium_version_string')) {
107
                $status['libsodium']['text']      = new XenForo_Phrase('option_threema_gateway_status_libsodium_version', ['version' => Sodium::sodium_version_string()]);
108
                $status['libsodium']['descr']     = new XenForo_Phrase('option_threema_gateway_status_libsodium_outdated');
109
                $status['libsodium']['descclass'] = 'warning';
110
            } else {
111
                $status['libsodium']['text'] = new XenForo_Phrase('option_threema_gateway_status_libsodium_version', ['version' => \Sodium\version_string()]);
112
            }
113
114
            // & libsodium-php
115
            $status['libsodiumphp']['text'] = new XenForo_Phrase('option_threema_gateway_status_libsodiumphp_version', ['version' => phpversion('libsodium')]);
116
            if (version_compare(phpversion('libsodium'), '1.0.1', '<')) {
117
                $status['libsodiumphp']['descr']     = new XenForo_Phrase('option_threema_gateway_status_libsodiumphp_outdated');
118
                $status['libsodiumphp']['descclass'] = 'warning';
119
            }
120
        } else {
121
            $status['libsodium']['text'] = new XenForo_Phrase('option_threema_gateway_status_libsodium_not_installed');
122 View Code Duplication
            if (PHP_INT_SIZE < 8) {
123
                $status['libsodium']['descr']         = new XenForo_Phrase('option_threema_gateway_status_libsodium_not_installed_required_64bit');
124
                $status['libsodium']['descclass']     = 'error';
125
                return false;
126
            } else {
127
                $status['libsodium']['descr']     = new XenForo_Phrase('option_threema_gateway_status_libsodium_not_installed_recommend');
128
                $status['libsodium']['descclass'] = 'warning';
129
            }
130
        }
131
132
        // there may be warnings, but apart from that all is okay
133
        return true;
134
    }
135
136
    /**
137
     * Checks whether the add-on/PHP-SDK is correctly configured and this ready
138
     * to use.
139
     *
140
     * It also automatically includes status indicators from the SDK.
141
     * Return false when a serious error happens, which indicates that the
142
     * requirements are not fullfilled.
143
     *
144
     * @param  array                           $status     Will be filled with required statuses (sic)
145
     * @param  array                           $extraError Optional other errors may be added here
146
     * @param  ThreemaGateway_Handler_Settings $gwSettings
147
     * @return bool
148
     */
149
    protected static function checkPhpSdk(array &$status, array &$extraError, ThreemaGateway_Handler_Settings $gwSettings = null)
150
    {
151
        // auto-create Gateway settings if not given
152
        if ($gwSettings === null) {
153
            $gwSettings = new ThreemaGateway_Handler_Settings;
154
        }
155
156
        //show PHP SDK version, checks if PHP-SDK is correctly setup
157
        try {
158
            $sdk = ThreemaGateway_Handler_PhpSdk::getInstance($gwSettings);
159
            //Note: When the SDK throws an exception the two lines below cannot be executed, so the version number cannot be determinated
160
            $status['phpsdk']['text']     = new XenForo_Phrase('option_threema_gateway_status_phpsdk_version', ['version' => $sdk->getVersion()]);
161
            $status['phpsdk']['addition'] = new XenForo_Phrase('option_threema_gateway_status_phpsdk_featurelevel', ['level' => $sdk->getFeatureLevel()]);
162
        } catch (Exception $e) {
163
            $extraError[]['text'] = new XenForo_Phrase('option_threema_gateway_status_custom_phpsdk_error') . $e->getMessage();
164
            return false;
165
        }
166
167
        // check whether Gateway is ready to use
168
        if (!$gwSettings->isReady()) {
169
            // If SDK is not ready, check whether it is at least available
170
            if ($gwSettings->isAvaliable()) {
171
                // presumambly an error in setup
172
                $extraError[]['text'] = new XenForo_Phrase('option_threema_gateway_status_phpsdk_not_ready');
173
            } else {
174
                // presumably not yet setup (default settings or so)
175
                $extraError[] = [
176
                    'text' => new XenForo_Phrase('option_threema_gateway_status_phpsdk_not_ready_yet'),
177
                    'descclass' => 'warning'
178
                ];
179
            }
180
181
            return false;
182
        }
183
184
        // there may be warnings, but apart from that all is okay
185
        return true;
186
    }
187
188
    /**
189
     * When the user is allowed to view the credits, this queries them and adds
190
     * the result as a status message.
191
     *
192
     * Return false when the permissions could not be fetched.
193
     * When the user has not enough permissions to do so, this method returns
194
     * true anyway.
195
     *
196
     * @param  array $status     Will be filled with required statuses (sic)
197
     * @param  array $extraError Optional other errors may be added here
198
     * @return bool
199
     */
200
    protected static function queryCredits(array &$status, array &$extraError)
201
    {
202
        /** @var ThreemaGateway_Handler_Permissions $permissions */
203
        $permissions = ThreemaGateway_Handler_Permissions::getInstance();
204
205
        // check permissions for accessing credits
206
        if (!$permissions->hasPermission('credits')) {
207
            $status['credits']['text']      = new XenForo_Phrase('option_threema_gateway_status_credits', ['credits' => 'No permission']);
208
            $status['credits']['descr']     = new XenForo_Phrase('option_threema_gateway_status_credits_permission');
209
            $status['credits']['descclass'] = 'warning';
210
211
            return true;
212
        }
213
214
        // always there credit text
215
        $status['credits']['addition'] = new XenForo_Phrase('option_threema_gateway_status_credits_recharge');
216
217
        // try to fetch credits
218
        try {
219
            $gwServer = new ThreemaGateway_Handler_Action_GatewayServer;
220
            /** @var int|string $credits */
221
            $credits = $gwServer->getCredits();
222
        } catch (Exception $e) {
223
            // special error handling
224
            $extraError[]['text'] = new XenForo_Phrase('option_threema_gateway_status_custom_gwserver_error') . $e->getMessage();
225
            $credits              = 'N/A';
226
227
            // add (general) status error
228
            $status['credits']['descr']     = new XenForo_Phrase('option_threema_gateway_status_credits_error');
229
            $status['credits']['descclass'] = 'error';
230
231
            // wanna use finally block here, but is only available in PHP >= 5.5 :(
232
            // so duplicate code…
233
            $status['credits']['text'] = new XenForo_Phrase('option_threema_gateway_status_credits', ['credits' => $credits]);
234
            return false;
235
        }
236
237
        // when no error happens, check whether credits are "enough"
238
        $status['credits']['text'] = new XenForo_Phrase('option_threema_gateway_status_credits', ['credits' => $credits]);
239 View Code Duplication
        if ($credits == 0) {
240
            $status['credits']['descr']     = new XenForo_Phrase('option_threema_gateway_status_credits_out');
241
            $status['credits']['descclass'] = 'error';
242
            return false;
243
        } elseif ($credits < self::CREDITS_WARN) {
244
            $status['credits']['descr']     = new XenForo_Phrase('option_threema_gateway_status_credits_low');
245
            $status['credits']['descclass'] = 'warning';
246
        }
247
248
        // there may be warnings, but apart from that all is okay
249
        return true;
250
    }
251
}
252