Skip to content

Commit

Permalink
Improve code quality.
Browse files Browse the repository at this point in the history
  • Loading branch information
terrylinooo committed Jun 19, 2020
1 parent d4dce21 commit 3a56839
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
39 changes: 10 additions & 29 deletions src/Psr17/UriFactory.php
Expand Up @@ -48,6 +48,7 @@ public static function fromGlobal(): UriInterface
$user = '';
$host = '';
$pass = '';
$path = '';
$port = '';
$query = '';
$scheme = '';
Expand All @@ -66,38 +67,18 @@ public static function fromGlobal(): UriInterface
${$key} = $server[$value] ?? '';
}

$userInfo = $user;
$userInfo = $user ? $user . ($pass ? ":{$pass}" : '') : '';

if ($pass) {
$userInfo .= ':' . $pass;
}

$authority = '';

if ($userInfo) {
$authority .= $userInfo . '@';
}

$authority .= $host;

if ($port) {
$authority .= ':' . $port;
}

if ($scheme) {
$uri .= $scheme . ':';
}
$authority = ($userInfo ? "{$userInfo}@": '')
. $host
. ($port ? ":{$port}" : '');

if ($authority) {
$uri .= '//' . $authority;
}

$uri .= '/' . ltrim($path, '/');
$uri = ($scheme ? "{$scheme}:" : '')
. ($authority ? "//{$authority}" : '')
. '/'
. ltrim($path, '/')
. ($query ? "?{$query}" : '');

if ($query) {
$uri .= '?' . $query;
}

return new Uri($uri);
}
}
24 changes: 24 additions & 0 deletions tests/Psr17/UriFactoryTest.php
Expand Up @@ -13,6 +13,7 @@
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\UriInterface;
use Shieldon\Psr17\UriFactory;
use Shieldon\Psr17\Utils\SuperGlobal;

class UriFactoryTest extends TestCase
{
Expand All @@ -23,4 +24,27 @@ public function test_createUri()
$uri = $uriFactory->createUri();
$this->assertTrue(($uri instanceof UriInterface));
}

public function test_fromGlobal()
{
SuperGlobal::mockCliEnvironment([
'PHP_AUTH_USER' => 'terry', // user
'HTTP_HOST' => 'example.org', // host
'PHP_AUTH_PW' => '1234', // pass
'REQUEST_URI' => '/test', // path
'SERVER_PORT' => '8080', // port
'QUERY_STRING' => 'foo=bar', // query
'REQUEST_SCHEME' => 'https', // scheme
]);

$uri = uriFactory::fromGlobal();

$this->assertSame($uri->getScheme(), 'https');
$this->assertSame($uri->getHost(), 'example.org');
$this->assertSame($uri->getUserInfo(), 'terry:1234'); // string
$this->assertSame($uri->getPath(), '/test'); // string
$this->assertSame($uri->getPort(), 8080); // int|null
$this->assertSame($uri->getQuery(), 'foo=bar'); // string
$this->assertSame($uri->getFragment(), ''); // string
}
}

0 comments on commit 3a56839

Please sign in to comment.