Completed
Push — master ( f83dd1...9493b0 )
by Armando
02:01 queued 01:03
created

Params::validateAndSetBotParamsSpecial()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 4
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)
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']['url'] ?? null) && !($params['secret'] ?? null)) {
156
            // This does not apply when using CLI, but make sure it gets tested for!
157
            if ('cli' !== PHP_SAPI || BotManager::inTest()) {
158
                throw new InvalidParamsException('Some vital info is missing: secret');
159
            }
160
        }
161
    }
162
163
    /**
164
     * Set all extra params.
165
     *
166
     * @param array $params
167
     */
168
    private function validateAndSetBotParamsExtra(array $params)
169
    {
170
        foreach (self::$valid_extra_bot_params as $extra_key) {
171
            if (!array_key_exists($extra_key, $params)) {
172
                continue;
173
            }
174
175
            $this->bot_params[$extra_key] = $params[$extra_key];
176
        }
177
    }
178
179
    /**
180
     * Handle all script params, via web server handler or CLI.
181
     *
182
     * https://url/entry.php?s=<secret>&a=<action>&l=<loop>
183
     * $ php entry.php s=<secret> a=<action> l=<loop>
184
     *
185
     * @return \TelegramBot\TelegramBotManager\Params
186
     */
187
    private function validateAndSetScriptParams(): self
188
    {
189
        $this->setScriptParams();
190
        $this->validateScriptParams();
191
192
        return $this;
193
    }
194
195
    /**
196
     * Set script parameters from query string or CLI.
197
     */
198
    private function setScriptParams()
199
    {
200
        $this->script_params = $_GET;
201
202
        // If we're not running from CLI, script parameters are already set from $_GET.
203
        if ('cli' !== PHP_SAPI) {
204
            return;
205
        }
206
207
        // We don't need the first arg (the file name).
208
        $args = array_slice($_SERVER['argv'], 1);
209
210
        /** @var array $args */
211
        foreach ($args as $arg) {
212
            @list($key, $val) = explode('=', $arg);
213
            isset($key, $val) && $this->script_params[$key] = $val;
214
        }
215
    }
216
217
    /**
218
     * Keep only valid script parameters.
219
     */
220
    private function validateScriptParams()
221
    {
222
        $this->script_params = array_intersect_key(
223
            $this->script_params,
224
            array_fill_keys(self::$valid_script_params, null)
225
        );
226
    }
227
228
    /**
229
     * Get a specific bot param, allowing array-dot notation.
230
     *
231
     * @param string $param
232
     * @param mixed  $default
233
     *
234
     * @return mixed
235
     */
236
    public function getBotParam(string $param, $default = null)
237
    {
238
        $param_path = explode('.', $param);
239
240
        $value = $this->bot_params[array_shift($param_path)] ?? null;
241
        foreach ($param_path as $sub_param_key) {
242
            $value = $value[$sub_param_key] ?? null;
243
            if (null === $value) {
244
                break;
245
            }
246
        }
247
248
        return $value ?? $default;
249
    }
250
251
    /**
252
     * Get an array of all bot params.
253
     *
254
     * @return array
255
     */
256
    public function getBotParams(): array
257
    {
258
        return $this->bot_params;
259
    }
260
261
    /**
262
     * Get a specific script param.
263
     *
264
     * @param string $param
265
     * @param mixed  $default
266
     *
267
     * @return mixed
268
     */
269
    public function getScriptParam(string $param, $default = null)
270
    {
271
        return $this->script_params[$param] ?? $default;
272
    }
273
274
    /**
275
     * Get an array of all script params.
276
     *
277
     * @return array
278
     */
279
    public function getScriptParams(): array
280
    {
281
        return $this->script_params;
282
    }
283
}
284