Completed
Pull Request — develop (#23)
by Armando
01:45
created

Params::validateAndSetBotParams()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 27
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 12
nc 9
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)
1 ignored issue
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 $params
114
     *
115
     * @return \TelegramBot\TelegramBotManager\Params
116
     * @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
117
     */
118
    private function validateAndSetBotParams($params): self
119
    {
120
        // Set all vital params.
121
        foreach (self::$valid_vital_bot_params as $vital_key) {
122
            if (!array_key_exists($vital_key, $params)) {
123
                throw new InvalidParamsException('Some vital info is missing: ' . $vital_key);
124
            }
125
126
            $this->bot_params[$vital_key] = $params[$vital_key];
127
        }
128
129
        // Special case, where secret MUST be defined if we have a webhook.
130
        if (($params['webhook'] ?? null) && !($params['secret'] ?? null)) {
131
            throw new InvalidParamsException('Some vital info is missing: secret');
132
        }
133
134
        // Set all extra params.
135
        foreach (self::$valid_extra_bot_params as $extra_key) {
136
            if (!array_key_exists($extra_key, $params)) {
137
                continue;
138
            }
139
140
            $this->bot_params[$extra_key] = $params[$extra_key];
141
        }
142
143
        return $this;
144
    }
145
146
    /**
147
     * Handle all script params, via web server handler or CLI.
148
     *
149
     * https://url/entry.php?s=<secret>&a=<action>&l=<loop>
150
     * $ php entry.php s=<secret> a=<action> l=<loop>
151
     *
152
     * @return \TelegramBot\TelegramBotManager\Params
153
     */
154
    private function validateAndSetScriptParams(): self
155
    {
156
        $this->script_params = $_GET;
157
158
        // If we're running from CLI, properly set script parameters.
159
        if ('cli' === PHP_SAPI) {
160
            // We don't need the first arg (the file name).
161
            $args = array_slice($_SERVER['argv'], 1);
162
163
            /** @var array $args */
164
            foreach ($args as $arg) {
165
                @list($key, $val) = explode('=', $arg);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
166
                isset($key, $val) && $this->script_params[$key] = $val;
167
            }
168
        }
169
170
        // Keep only valid ones.
171
        $this->script_params = array_intersect_key(
172
            $this->script_params,
173
            array_fill_keys(self::$valid_script_params, null)
174
        );
175
176
        return $this;
177
    }
178
179
    /**
180
     * Get a specific bot param, allowing array-dot notation.
181
     *
182
     * @param string $param
183
     * @param mixed  $default
184
     *
185
     * @return mixed
186
     */
187
    public function getBotParam(string $param, $default = null)
188
    {
189
        $param_path = explode('.', $param);
190
191
        $value = $this->bot_params[array_shift($param_path)] ?? null;
192
        foreach ($param_path as $sub_param_key) {
193
            $value = $value[$sub_param_key] ?? null;
194
            if (null === $value) {
195
                break;
196
            }
197
        }
198
199
        return $value ?? $default;
200
    }
201
202
    /**
203
     * Get an array of all bot params.
204
     *
205
     * @return array
206
     */
207
    public function getBotParams(): array
208
    {
209
        return $this->bot_params;
210
    }
211
212
    /**
213
     * Get a specific script param.
214
     *
215
     * @param string $param
216
     * @param mixed  $default
217
     *
218
     * @return mixed
219
     */
220
    public function getScriptParam(string $param, $default = null)
221
    {
222
        return $this->script_params[$param] ?? $default;
223
    }
224
225
    /**
226
     * Get an array of all script params.
227
     *
228
     * @return array
229
     */
230
    public function getScriptParams(): array
231
    {
232
        return $this->script_params;
233
    }
234
}
235