Completed
Branch develop (340e70)
by Armando
03:17
created

Params::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
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 NPM\TelegramBotManager;
12
13
class Params
14
{
15
    /**
16
     * @var array List of valid script parameters.
17
     */
18
    private static $valid_script_params = [
19
        's',
20
        'a',
21
        'l',
22
    ];
23
24
    /**
25
     * @var array List of vital parameters that must be passed.
26
     */
27
    private static $valid_vital_bot_params = [
28
        'api_key',
29
        'botname',
30
        'secret',
31
    ];
32
33
    /**
34
     * @var array List of valid extra parameters that can be passed.
35
     */
36
    private static $valid_extra_bot_params = [
37
        'webhook',
38
        'selfcrt',
39
        'logging',
40
        'admins',
41
        'mysql',
42
        'download_path',
43
        'upload_path',
44
        'commands_paths',
45
        'command_configs',
46
        'botan_token',
47
        'custom_input',
48
    ];
49
50
    /**
51
     * @var array List of all params passed to the script.
52
     */
53
    private $script_params = [];
54
55
    /**
56
     * @var array List of all params passed at construction.
57
     */
58
    private $bot_params = [];
59
60
    /**
61
     * Params constructor.
62
     *
63
     * api_key (string) Telegram Bot API key
64
     * botname (string) Telegram Bot name
65
     * secret (string) Secret string to validate calls
66
     * webhook (string) URI of the webhook
67
     * selfcrt (string) Path to the self-signed certificate
68
     * logging (array) Array of logger files to set.
69
     * admins (array) List of admins to enable.
70
     * mysql (array) MySQL credentials to use.
71
     * download_path (string) Custom download path to set.
72
     * upload_path (string) Custom upload path to set.
73
     * commands_paths (array) Custom commands paths to set.
74
     * command_configs (array) List of custom command configs.
75
     * botan_token (string) Botan token to enable botan.io support.
76
     * custom_input (string) Custom raw JSON string to use as input.
77
     *
78
     * @param array $params All params to set the bot up with.
79
     *
80
     * @throws \InvalidArgumentException
81
     */
82
    public function __construct(array $params)
83
    {
84
        $this->validateAndSetBotParams($params);
85
        $this->validateAndSetScriptParams();
86
    }
87
88
    /**
89
     * Validate and set up the vital and extra params.
90
     *
91
     * @param $params
92
     *
93
     * @throws \InvalidArgumentException
94
     */
95
    private function validateAndSetBotParams($params)
96
    {
97
        // Set all vital params.
98
        foreach (self::$valid_vital_bot_params as $vital_key) {
99
            if (empty($params[$vital_key])) {
100
                throw new \InvalidArgumentException('Some vital info is missing: ' . $vital_key);
101
            }
102
103
            $this->bot_params[$vital_key] = $params[$vital_key];
104
        }
105
106
        // Set all extra params.
107
        foreach (self::$valid_extra_bot_params as $extra_key) {
108
            if (empty($params[$extra_key])) {
109
                continue;
110
            }
111
112
            $this->bot_params[$extra_key] = $params[$extra_key];
113
        }
114
    }
115
116
    /**
117
     * Handle all script params, via web server handler or CLI.
118
     *
119
     * https://url/entry.php?s=<secret>&a=<action>&l=<loop>
120
     * $ php entry.php s=<secret> a=<action> l=<loop>
121
     */
122
    private function validateAndSetScriptParams()
2 ignored issues
show
Coding Style introduced by
validateAndSetScriptParams uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
validateAndSetScriptParams uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
123
    {
124
        $this->script_params = $_GET;
125
126
        // If we're running from CLI, properly set script parameters.
127
        if ('cli' === PHP_SAPI) {
128
            // We don't need the first arg (the file name).
129
            $args = array_slice($_SERVER['argv'], 1);
130
131
            foreach ($args as $arg) {
132
                @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...
133
                isset($key, $val) && $this->script_params[$key] = $val;
134
            }
135
        }
136
137
        // Keep only valid ones.
138
        $this->script_params = array_intersect_key($this->script_params,
139
            array_fill_keys(self::$valid_script_params, null));
140
141
        return $this;
142
    }
143
144
    /**
145
     * Get a specific bot param.
146
     *
147
     * @param string $param
148
     *
149
     * @return mixed
150
     */
151
    public function getBotParam($param)
152
    {
153
        return isset($this->bot_params[$param]) ? $this->bot_params[$param] : null;
154
    }
155
156
    public function getBotParams()
157
    {
158
        return $this->bot_params;
159
    }
160
161
    /**
162
     * Get a specific script param.
163
     *
164
     * @param string $param
165
     *
166
     * @return mixed
167
     */
168
    public function getScriptParam($param)
169
    {
170
        return isset($this->script_params[$param]) ? $this->script_params[$param] : null;
171
    }
172
173
    public function getScriptParams()
174
    {
175
        return $this->script_params;
176
    }
177
}
178