Improve Proxy::shouldBeUsed (#13702)

* Improve Proxy::shouldBeUsed

* Update Proxy.php

* Create ProxyTest.php

* Update ProxyTest.php

* Update Proxy.php
This commit is contained in:
Jellyfrog
2022-01-24 21:55:52 +01:00
committed by GitHub
parent f4f297fd48
commit 8b67feabd7
2 changed files with 47 additions and 5 deletions

View File

@@ -35,7 +35,7 @@ class Proxy
*/
public static function shouldBeUsed(string $target_url): bool
{
return (bool) preg_match('#//:(localhost|127\.|::1)#', $target_url);
return preg_match('#(^|://)(localhost|127\.|::1)#', $target_url) == 0;
}
/**
@@ -63,9 +63,9 @@ class Proxy
/**
* Return the proxy url in guzzle format "http://127.0.0.1:8888"
*/
public static function forGuzzle(): string
public static function forGuzzle(?string $target_url = null): string
{
$proxy = self::forCurl();
$proxy = self::forCurl($target_url);
return empty($proxy) ? '' : ('http://' . $proxy);
}
@@ -75,9 +75,9 @@ class Proxy
*
* @return string
*/
public static function forCurl(): string
public static function forCurl(?string $target_url = null): string
{
return str_replace(['http://', 'https://'], '', rtrim(self::get(), '/'));
return str_replace(['http://', 'https://'], '', rtrim(self::get($target_url), '/'));
}
/**

42
tests/ProxyTest.php Normal file
View File

@@ -0,0 +1,42 @@
<?php
/**
* ProxyTest.php
*
* Tests Util\Proxy classes
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @link https://www.librenms.org
*/
namespace LibreNMS\Tests;
use LibreNMS\Util\Proxy;
class ProxyTest extends TestCase
{
public function testShouldBeUsed(): void
{
$this->assertTrue(Proxy::shouldBeUsed('http://example.com/foobar'));
$this->assertTrue(Proxy::shouldBeUsed('foo/bar'));
$this->assertTrue(Proxy::shouldBeUsed('192.168.0.1'));
$this->assertTrue(Proxy::shouldBeUsed('2001:db8::8a2e:370:7334'));
$this->assertFalse(Proxy::shouldBeUsed('http://localhost/foobar'));
$this->assertFalse(Proxy::shouldBeUsed('localhost/foobar'));
$this->assertFalse(Proxy::shouldBeUsed('127.0.0.1'));
$this->assertFalse(Proxy::shouldBeUsed('127.0.0.1:1337'));
$this->assertFalse(Proxy::shouldBeUsed('::1'));
}
}