Skip to content

Commit a1a131b

Browse files
committed
Fix script to work from CLI, as there is no IP defined when called from CLI.
Add helper to determine if we're running in a test.
1 parent fdd38c5 commit a1a131b

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/BotManager.php

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ public function __construct(array $params)
6666
$this->action = new Action($this->params->getScriptParam('a'));
6767
}
6868

69+
/**
70+
* Check if we're busy running the PHPUnit tests.
71+
*
72+
* @return bool
73+
*/
74+
public static function inTest(): bool
75+
{
76+
return defined('PHPUNIT_TEST') && PHPUNIT_TEST === true;
77+
}
78+
6979
/**
7080
* Return the Telegram object.
7181
*
@@ -221,7 +231,7 @@ private function handleOutput($output): self
221231
{
222232
$this->output .= $output;
223233

224-
if (!(defined('PHPUNIT_TEST') && PHPUNIT_TEST === true)) {
234+
if (!self::inTest()) {
225235
echo $output;
226236
}
227237

@@ -433,13 +443,13 @@ public function getOutput(): string
433443
*/
434444
public function isValidRequest(): bool
435445
{
436-
if (false === $this->params->getBotParam('validate_request')) {
446+
if ((!self::inTest() && 'cli' === PHP_SAPI) || false === $this->params->getBotParam('validate_request')) {
437447
return true;
438448
}
439449

440-
$ip = @$_SERVER['REMOTE_ADDR'];
450+
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
441451
foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'] as $key) {
442-
$addr = @$_SERVER[$key];
452+
$addr = $_SERVER[$key] ?? null;
443453
if (filter_var($addr, FILTER_VALIDATE_IP)) {
444454
$ip = $addr;
445455
break;

tests/TelegramBotManager/Tests/BotManagerTest.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ public function testSetParameters()
5656
self::assertNull($params->getBotParam('paramX'));
5757
}
5858

59+
public function testInTest()
60+
{
61+
self::assertTrue(BotManager::inTest());
62+
}
63+
5964
/**
6065
* @expectedException \InvalidArgumentException
6166
* @expectedExceptionMessage Some vital info is missing: api_key
@@ -383,7 +388,7 @@ public function testIsValidRequestFailValidation()
383388

384389
unset($_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_CLIENT_IP'], $_SERVER['REMOTE_ADDR']);
385390

386-
foreach(['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'] as $key) {
391+
foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'] as $key) {
387392
$_SERVER[$key] = '1.1.1.1';
388393
self::assertFalse($botManager->isValidRequest());
389394
unset($_SERVER[$key]);

0 commit comments

Comments
 (0)