Skip to content

Commit 818027b

Browse files
committed
Allow CLI call to skip secret and action validations.
More complete DocBlocks. Add editorconfig.
1 parent 55fcd6b commit 818027b

File tree

3 files changed

+124
-44
lines changed

3 files changed

+124
-44
lines changed

.editorconfig

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
root = true
2+
3+
[*]
4+
end_of_line = lf
5+
insert_final_newline = true
6+
charset = utf-8
7+
indent_style = space
8+
indent_size = 4
9+
trim_trailing_whitespace = true

src/BotManager.php

Lines changed: 98 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -33,31 +33,83 @@ class BotManager
3333
*/
3434
public $test_output;
3535

36-
/** vitals */
37-
public $api_key;
36+
/**
37+
* @var string Telegram Bot API key
38+
*/
39+
protected $api_key = '';
40+
41+
/**
42+
* @var string Telegram Bot name
43+
*/
3844
public $botname;
45+
46+
/**
47+
* @var string Secret string to validate calls
48+
*/
3949
public $secret;
4050

41-
public $action;
51+
/**
52+
* @var string Action to be executed
53+
*/
54+
public $action = 'handle';
55+
56+
/**
57+
* @var string URI of the webhook
58+
*/
4259
public $webhook;
60+
61+
/**
62+
* @var string Path to the self-signed certificate
63+
*/
4364
public $selfcrt;
4465

45-
/**
46-
* BotManager constructor that assigns all necessary member variables.
47-
*
48-
* @param array $vars
49-
*
50-
* @throws \Exception
51-
*/
66+
/**
67+
* @var array List of valid actions that can be called
68+
*/
69+
private static $valid_actions = [
70+
'set',
71+
'unset',
72+
'reset',
73+
'handle'
74+
];
75+
76+
/**
77+
* @var array List of valid extra parameters that can be passed
78+
*/
79+
private static $valid_params = [
80+
'api_key',
81+
'botname',
82+
'secret',
83+
'webhook',
84+
'selfcrt',
85+
'logging',
86+
'admins',
87+
'mysql',
88+
'download_path',
89+
'upload_path',
90+
'commands_paths',
91+
'command_configs',
92+
'botan_token',
93+
'custom_input'
94+
];
95+
96+
97+
/**
98+
* BotManager constructor that assigns all necessary member variables.
99+
*
100+
* @param array $vars
101+
*
102+
* @throws \Exception
103+
*/
52104
public function __construct(array $vars)
53105
{
54106
if (!isset($vars['api_key'], $vars['botname'], $vars['secret'])) {
55107
throw new \Exception('Some vital info is missing (api_key, botname or secret)');
56108
}
57109

58-
// Set all important info.
110+
// Set all vital and extra parameters.
59111
foreach ($vars as $var => $value) {
60-
$this->$var = $value;
112+
in_array($var, self::$valid_params, true) && $this->$var = $value;
61113
}
62114
}
63115

@@ -94,6 +146,16 @@ public function run()
94146
return $this;
95147
}
96148

149+
/**
150+
* Check if this script is being called from CLI.
151+
*
152+
* @return bool
153+
*/
154+
public function isCli()
155+
{
156+
return PHP_SAPI === 'cli';
157+
}
158+
97159
/**
98160
* Allow this script to be called via CLI.
99161
*
@@ -102,7 +164,7 @@ public function run()
102164
public function makeCliFriendly()
103165
{
104166
// If we're running from CLI, properly set $_GET.
105-
if (PHP_SAPI === 'cli') {
167+
if ($this->isCli()) {
106168
// We don't need the first arg (the file name).
107169
$args = array_slice($_SERVER['argv'], 1);
108170

@@ -134,13 +196,19 @@ public function initLogging()
134196
/**
135197
* Make sure the passed secret is valid.
136198
*
199+
* @param bool $force Force validation, even on CLI.
200+
*
201+
* @return $this
137202
* @throws \Exception
138203
*/
139-
public function validateSecret()
204+
public function validateSecret($force = false)
140205
{
141-
$secretGet = isset($_GET['s']) ? (string)$_GET['s'] : '';
142-
if (empty($this->secret) || $secretGet !== $this->secret) {
143-
throw new \Exception('Invalid access');
206+
// If we're running from CLI, secret isn't necessary.
207+
if ($force || !$this->isCli()) {
208+
$secretGet = isset($_GET['s']) ? (string)$_GET['s'] : '';
209+
if (empty($this->secret) || $secretGet !== $this->secret) {
210+
throw new \Exception('Invalid access');
211+
}
144212
}
145213

146214
return $this;
@@ -153,9 +221,10 @@ public function validateSecret()
153221
*/
154222
public function validateAndSetAction()
155223
{
156-
$validActions = ['set', 'unset', 'reset', 'handle'];
157-
$this->action = isset($_GET['a']) ? (string)$_GET['a'] : '';
158-
if (!$this->isAction($validActions)) {
224+
// Only set the action if it has been passed, else use the default.
225+
isset($_GET['a']) && $this->action = (string)$_GET['a'];
226+
227+
if (!$this->isAction(self::$valid_actions)) {
159228
throw new \Exception('Invalid action');
160229
}
161230

@@ -177,7 +246,10 @@ public function validateAndSetWebhook()
177246
$this->test_output = $this->telegram->unsetWebHook()->getDescription();
178247
}
179248
if ($this->isAction(['set', 'reset'])) {
180-
$this->test_output = $this->telegram->setWebHook($this->webhook . '?a=handle&s=' . $this->secret, $this->selfcrt)->getDescription();
249+
$this->test_output = $this->telegram->setWebHook(
250+
$this->webhook . '?a=handle&s=' . $this->secret,
251+
$this->selfcrt
252+
)->getDescription();
181253
}
182254

183255
(@constant('PHPUNIT_TEST') !== true) && print($this->test_output . PHP_EOL);
@@ -243,6 +315,8 @@ public function handleRequest()
243315
* Loop the getUpdates method for the passed amount of seconds.
244316
*
245317
* @param $loop_time_in_seconds int
318+
*
319+
* @return $this
246320
*/
247321
public function handleGetUpdatesLoop($loop_time_in_seconds)
248322
{
@@ -277,15 +351,15 @@ public function handleGetUpdates()
277351
/** @var Entities\Update $result */
278352
foreach ($results as $result) {
279353
$chat_id = 0;
280-
$text = 'Nothing';
354+
$text = 'Nothing';
281355

282356
$update_content = $result->getUpdateContent();
283357
if ($update_content instanceof Entities\Message) {
284358
$chat_id = $update_content->getFrom()->getId();
285-
$text = $update_content->getText();
359+
$text = $update_content->getText();
286360
} elseif ($update_content instanceof Entities\InlineQuery || $update_content instanceof Entities\ChosenInlineResult) {
287361
$chat_id = $update_content->getFrom()->getId();
288-
$text = $update_content->getQuery();
362+
$text = $update_content->getQuery();
289363
}
290364

291365
printf(

tests/BotManagerTest.php

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,13 @@ public function setUp()
6363
public function testSetParameters()
6464
{
6565
$botManager = new BotManager(array_merge($this->vitalParams, [
66-
'param1' => 'param1value',
67-
'param2' => 'param2value',
68-
'param3' => 'param3value',
66+
'admins' => 1, // valid
67+
'upload_path' => '/upload/path', // valid
68+
'paramX' => 'something' // invalid
6969
]));
70-
self::assertEquals('param1value', $botManager->param1);
71-
self::assertEquals('param2value', $botManager->param2);
72-
self::assertEquals('param3value', $botManager->param3);
73-
74-
self::assertObjectNotHasAttribute('param4', $botManager);
70+
self::assertEquals(1, $botManager->admins);
71+
self::assertEquals('/upload/path', $botManager->upload_path);
72+
self::assertObjectNotHasAttribute('paramX', $botManager);
7573
}
7674

7775
/**
@@ -161,24 +159,20 @@ public function testValidateSecretFail()
161159
$_GET = ['s' => 'NOT_my_secret_12345'];
162160
$botManager = new BotManager(array_merge($this->vitalParams, ['secret' => 'my_secret_12345']));
163161

164-
$botManager->validateSecret();
162+
$botManager->validateSecret(true);
165163
}
166164

167165
public function testValidateSecretSuccess()
168166
{
169-
$_GET = ['s' => 'my_secret_12345'];
170167
$botManager = new BotManager(array_merge($this->vitalParams, ['secret' => 'my_secret_12345']));
171168

172-
self::assertEquals($botManager, $botManager->validateSecret());
173-
}
169+
// Force validation to test non-CLI scenario.
170+
$_GET = ['s' => 'my_secret_12345'];
171+
$botManager->validateSecret(true);
174172

175-
/**
176-
* @expectedException \Exception
177-
* @expectedExceptionMessage Invalid action
178-
*/
179-
public function testValidateAndSetActionFailWithoutAction()
180-
{
181-
(new BotManager($this->vitalParams))->validateAndSetAction();
173+
// Calling from CLI doesn't require a secret.
174+
$_GET = ['s' => 'whatever_on_cli'];
175+
$botManager->validateSecret();
182176
}
183177

184178
/**
@@ -195,6 +189,9 @@ public function testValidateAndSetActionSuccess()
195189
{
196190
$botManager = new BotManager($this->vitalParams);
197191

192+
// Default value.
193+
self::assertEquals('handle', $botManager->validateAndSetAction()->action);
194+
198195
$validActions = ['set', 'unset', 'reset', 'handle'];
199196
foreach ($validActions as $action) {
200197
$_GET = ['a' => $action];
@@ -220,7 +217,7 @@ public function testValidateAndSetWebhookSuccess()
220217
$botManager->telegram->expects(static::any())
221218
->method('getDescription')
222219
->will(static::onConsecutiveCalls(
223-
// set
220+
// set
224221
'Webhook set',
225222
'Webhook already set',
226223
// unset

0 commit comments

Comments
 (0)