From 2c663fffd46158767bfc9af9b586b8a4963add6e Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Fri, 26 May 2023 14:18:58 +0200 Subject: [PATCH] Add helper functions in Forwarded class. + `Forwarded::get()` to get the parsed `Forwarded` header. + `Forwarded::getOriginIp()` to get the IP address of the origin of the request directly. --- src/Forwarded.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/Forwarded.php b/src/Forwarded.php index d410658..37cfffb 100644 --- a/src/Forwarded.php +++ b/src/Forwarded.php @@ -68,4 +68,26 @@ class Forwarded { return $this->forwards; } + + + /** + * Get the forward chain from the HTTP header found in `$_SERVER["HTTP_FORWARDED"]`. + * @return Forwarded - The parsed Forwarded header. + * @throws EmptyNodeNameException + */ + public static function get(): Forwarded + { + return (new Parser())->parseHttpHeader(); + } + + /** + * Try to get the IP address of the origin of the request. + * @return string|null - The IP address of the origin of the request, if there is one. + * @throws Exceptions\NotIpAddressException + * @throws EmptyNodeNameException + */ + public static function getOriginIp(): string|null + { + return self::get()?->first()?->for()?->getIp() ?? null; + } }