Skip to content

Commit

Permalink
added Request::getOrigin()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Apr 2, 2022
1 parent eab2f01 commit 65bfe68
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,22 @@ public function getReferer(): ?UrlImmutable
}


/**
* What origin did the user come from? It contains scheme, hostname and port.
*/
public function getOrigin(): ?UrlImmutable
{
$header = $this->headers['origin'] ?? 'null';
try {
return $header === 'null'
? null
: new UrlImmutable($header);
} catch (Nette\InvalidArgumentException $e) {
return null;
}
}


/**
* Is the request sent via secure channel (https)?
*/
Expand Down
40 changes: 40 additions & 0 deletions tests/Http/Request.getOrigin.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

use Nette\Http;
use Nette\Http\UrlImmutable;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


test('missing origin', function () {
$_SERVER = [];
$factory = new Http\RequestFactory;
$request = $factory->fromGlobals();

Assert::null($request->getOrigin());
});


test('opaque origin', function () {
$_SERVER = [
'HTTP_ORIGIN' => 'null',
];
$factory = new Http\RequestFactory;
$request = $factory->fromGlobals();

Assert::null($request->getOrigin());
});


test('normal origin', function () {
$_SERVER = [
'HTTP_ORIGIN' => 'https://nette.org',
];
$factory = new Http\RequestFactory;
$request = $factory->fromGlobals();

Assert::equal(new UrlImmutable('https://nette.org'), $request->getOrigin());
});

0 comments on commit 65bfe68

Please sign in to comment.