Skip to content

Commit 65bfe68

Browse files
committed
added Request::getOrigin()
1 parent eab2f01 commit 65bfe68

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Http/Request.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,22 @@ public function getReferer(): ?UrlImmutable
241241
}
242242

243243

244+
/**
245+
* What origin did the user come from? It contains scheme, hostname and port.
246+
*/
247+
public function getOrigin(): ?UrlImmutable
248+
{
249+
$header = $this->headers['origin'] ?? 'null';
250+
try {
251+
return $header === 'null'
252+
? null
253+
: new UrlImmutable($header);
254+
} catch (Nette\InvalidArgumentException $e) {
255+
return null;
256+
}
257+
}
258+
259+
244260
/**
245261
* Is the request sent via secure channel (https)?
246262
*/

tests/Http/Request.getOrigin.phpt

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Http;
6+
use Nette\Http\UrlImmutable;
7+
use Tester\Assert;
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
test('missing origin', function () {
13+
$_SERVER = [];
14+
$factory = new Http\RequestFactory;
15+
$request = $factory->fromGlobals();
16+
17+
Assert::null($request->getOrigin());
18+
});
19+
20+
21+
test('opaque origin', function () {
22+
$_SERVER = [
23+
'HTTP_ORIGIN' => 'null',
24+
];
25+
$factory = new Http\RequestFactory;
26+
$request = $factory->fromGlobals();
27+
28+
Assert::null($request->getOrigin());
29+
});
30+
31+
32+
test('normal origin', function () {
33+
$_SERVER = [
34+
'HTTP_ORIGIN' => 'https://nette.org',
35+
];
36+
$factory = new Http\RequestFactory;
37+
$request = $factory->fromGlobals();
38+
39+
Assert::equal(new UrlImmutable('https://nette.org'), $request->getOrigin());
40+
});

0 commit comments

Comments
 (0)