Completed
Push — develop ( eb794c...427bed )
by Armando
02:08
created

Params::validateAndSetBotParamsVital()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the TelegramBotManager package.
4
 *
5
 * (c) Armando Lüscher <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace TelegramBot\TelegramBotManager;
12
13
use TelegramBot\TelegramBotManager\Exception\InvalidParamsException;
14
15
class Params
16
{
17
    /**
18
     * @var array List of valid script parameters.
19
     */
20
    private static $valid_script_params = [
21
        's', // secret
22
        'a', // action
23
        'l', // loop
24
        'i', // interval
25
        'g', // group (for cron)
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
26
    ];
27
28
    /**
29
     * @var array List of vital parameters that must be passed.
30
     */
31
    private static $valid_vital_bot_params = [
32
        'api_key',
33
    ];
34
35
    /**
36
     * @var array List of valid extra parameters that can be passed.
37
     */
38
    private static $valid_extra_bot_params = [
39
        'bot_username',
40
        'secret',
41
        'validate_request',
42
        'valid_ips',
43
        'webhook',
44
        'logging',
45
        'limiter',
46
        'admins',
47
        'mysql',
48
        'paths',
49
        'commands',
50
        'botan',
51
        'cron',
52
        'custom_input',
53
    ];
54
55
    /**
56
     * @var array List of all params passed to the script.
57
     */
58
    private $script_params = [];
59
60
    /**
61
     * @var array List of all params passed at construction, predefined with defaults.
62
     */
63
    private $bot_params = [
64
        'validate_request' => true,
65
    ];
66
67
    /**
68
     * Params constructor.
69
     *
70
     * api_key (string) Telegram Bot API key
71
     * bot_username (string) Telegram Bot username
72
     * secret (string) Secret string to validate calls
73
     * validate_request (bool) Only allow webhook access from valid Telegram API IPs and defined valid_ips
74
     * valid_ips (array) Any IPs, besides Telegram API IPs, that are allowed to access the webhook
75
     * webhook (array)
76
     * - url (string) URI of the webhook
77
     * - certificate (string) Path to the self-signed certificate
78
     * - max_connections (int) Maximum allowed simultaneous HTTPS connections to the webhook
79
     * - allowed_updates (array) List the types of updates you want your bot to receive
80
     * logging (array) Array of logger files to set.
81
     * limiter (array)
82
     * - enabled (bool) Set limiter.
83
     * - options (array) Limiter options.
84
     * admins (array) List of admins to enable.
85
     * mysql (array) MySQL credentials to use.
86
     * paths (array)
87
     * - download (string) Custom download path to set.
88
     * - upload (string) Custom upload path to set.
89
     * commands (array)
90
     * - paths (array) Custom commands paths to set.
91
     * - configs (array) List of custom command configs.
92
     * botan (array)
93
     * - token (string) Botan token to enable botan.io support.
94
     * - options (array) Botan options.
95
     * custom_input (string) Custom raw JSON string to use as input.
96
     * cron (array)
97
     * - groups (array) Groups of cron commands to run.
98
     *   - default (array) Default group of cron commands.
99
     *
100
     * @param array $params All params to set the bot up with.
101
     *
102
     * @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
103
     */
104
    public function __construct(array $params)
105
    {
106
        $this->validateAndSetBotParams($params);
107
        $this->validateAndSetScriptParams();
108
    }
109
110
    /**
111
     * Validate and set up the vital and extra params.
112
     *
113
     * @param array $params
114
     *
115
     * @return \TelegramBot\TelegramBotManager\Params
116
     * @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
117
     */
118
    private function validateAndSetBotParams(array $params): self
119
    {
120
        $this->validateAndSetBotParamsVital($params);
121
        $this->validateAndSetBotParamsSpecial($params);
122
        $this->validateAndSetBotParamsExtra($params);
123
124
        return $this;
125
    }
126
127
    /**
128
     * Set all vital params.
129
     *
130
     * @param array $params
131
     *
132
     * @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
133
     */
134
    private function validateAndSetBotParamsVital(array $params)
135
    {
136
        foreach (self::$valid_vital_bot_params as $vital_key) {
137
            if (!array_key_exists($vital_key, $params)) {
138
                throw new InvalidParamsException('Some vital info is missing: ' . $vital_key);
139
            }
140
141
            $this->bot_params[$vital_key] = $params[$vital_key];
142
        }
143
    }
144
145
    /**
146
     * Special case parameters.
147
     *
148
     * @param array $params
149
     *
150
     * @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
151
     */
152
    private function validateAndSetBotParamsSpecial(array $params)
153
    {
154
        // Special case, where secret MUST be defined if we have a webhook.
155
        if (($params['webhook'] ?? null) && !($params['secret'] ?? null)) {
156
            throw new InvalidParamsException('Some vital info is missing: secret');
157
        }
158
    }
159
160
    /**
161
     * Set all extra params.
162
     *
163
     * @param array $params
164
     */
165
    private function validateAndSetBotParamsExtra(array $params)
166
    {
167
        foreach (self::$valid_extra_bot_params as $extra_key) {
168
            if (!array_key_exists($extra_key, $params)) {
169
                continue;
170
            }
171
172
            $this->bot_params[$extra_key] = $params[$extra_key];
173
        }
174
    }
175
176
    /**
177
     * Handle all script params, via web server handler or CLI.
178
     *
179
     * https://url/entry.php?s=<secret>&a=<action>&l=<loop>
180
     * $ php entry.php s=<secret> a=<action> l=<loop>
181
     *
182
     * @return \TelegramBot\TelegramBotManager\Params
183
     */
184
    private function validateAndSetScriptParams(): self
185
    {
186
        $this->setScriptParams();
187
        $this->validateScriptParams();
188
189
        return $this;
190
    }
191
192
    /**
193
     * Set script parameters from query string or CLI.
194
     */
195
    private function setScriptParams()
196
    {
197
        $this->script_params = $_GET;
198
199
        // If we're not running from CLI, script parameters are already set from $_GET.
200
        if ('cli' !== PHP_SAPI) {
201
            return;
202
        }
203
204
        // We don't need the first arg (the file name).
205
        $args = array_slice($_SERVER['argv'], 1);
206
207
        /** @var array $args */
208
        foreach ($args as $arg) {
209
            @list($key, $val) = explode('=', $arg);
210
            isset($key, $val) && $this->script_params[$key] = $val;
211
        }
212
    }
213
214
    /**
215
     * Keep only valid script parameters.
216
     */
217
    private function validateScriptParams()
218
    {
219
        $this->script_params = array_intersect_key(
220
            $this->script_params,
221
            array_fill_keys(self::$valid_script_params, null)
222
        );
223
    }
224
225
    /**
226
     * Get a specific bot param, allowing array-dot notation.
227
     *
228
     * @param string $param
229
     * @param mixed  $default
230
     *
231
     * @return mixed
232
     */
233
    public function getBotParam(string $param, $default = null)
234
    {
235
        $param_path = explode('.', $param);
236
237
        $value = $this->bot_params[array_shift($param_path)] ?? null;
238
        foreach ($param_path as $sub_param_key) {
239
            $value = $value[$sub_param_key] ?? null;
240
            if (null === $value) {
241
                break;
242
            }
243
        }
244
245
        return $value ?? $default;
246
    }
247
248
    /**
249
     * Get an array of all bot params.
250
     *
251
     * @return array
252
     */
253
    public function getBotParams(): array
254
    {
255
        return $this->bot_params;
256
    }
257
258
    /**
259
     * Get a specific script param.
260
     *
261
     * @param string $param
262
     * @param mixed  $default
263
     *
264
     * @return mixed
265
     */
266
    public function getScriptParam(string $param, $default = null)
267
    {
268
        return $this->script_params[$param] ?? $default;
269
    }
270
271
    /**
272
     * Get an array of all script params.
273
     *
274
     * @return array
275
     */
276
    public function getScriptParams(): array
277
    {
278
        return $this->script_params;
279
    }
280
}
281