From 2b937ac88b2f46761599fd8da6d81ebb08ea2ff8 Mon Sep 17 00:00:00 2001 From: Eser DENIZ Date: Sun, 24 Nov 2024 20:42:39 +0100 Subject: [PATCH] fix: get() should not throw exceptions --- README.md | 4 ++-- examples/ipv6.php | 2 ++ src/Abstracts/Finder.php | 15 ++++++++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3a2e16b..631071d 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,7 @@ $ipv4 = PublicIPv4::get(); // returns your IPv4 $ipv6 = PublicIPv6::get(); // returns your IPv6 $ipv4or6 = PublicIP::get(); // returns either IPv4 or IPv6 ``` - -[//]: # (Talk about the default configuration) +These methods return the IP address as a `string` or `null` if the fetcher fails. No exceptions are thrown. If you want to use a specific fetcher, or a specific provider, you can use the `PublicIPv4::finder()->fetch()` method. @@ -46,6 +45,7 @@ $ipv4 = PublicIPv4::finder() ->from(DnsProvider::OpenDNS))) ->fetch(); ``` +This method gives you more control, but you will need to manage exceptions on your own. ### Advanced Usage diff --git a/examples/ipv6.php b/examples/ipv6.php index 3ee8f96..71235d4 100644 --- a/examples/ipv6.php +++ b/examples/ipv6.php @@ -2,6 +2,8 @@ require_once __DIR__.'/../vendor/autoload.php'; +use KnotsPHP\PublicIP\Enums\DnsProvider; +use KnotsPHP\PublicIP\Fetchers\DigFetcher; use KnotsPHP\PublicIP\Finders\PublicIPv6; echo PublicIPv6::get(); diff --git a/src/Abstracts/Finder.php b/src/Abstracts/Finder.php index 6951eed..0258aa1 100644 --- a/src/Abstracts/Finder.php +++ b/src/Abstracts/Finder.php @@ -5,6 +5,7 @@ use KnotsPHP\PublicIP\Contracts\FetcherContract; use KnotsPHP\PublicIP\Contracts\FinderContract; use KnotsPHP\PublicIP\Enums\IpVersion; +use KnotsPHP\PublicIP\Exceptions\Exception; use KnotsPHP\PublicIP\Exceptions\IpAddressNotFound; use KnotsPHP\PublicIP\Exceptions\NoFetcherSpecified; use KnotsPHP\PublicIP\Exceptions\UnmatchedIpVersionReceived; @@ -53,8 +54,7 @@ public static function with(?FetcherContract $provider = null): static } /** - * @throws IpAddressNotFound - * @throws NoFetcherSpecified + * @throws NoFetcherSpecified|UnmatchedIpVersionReceived|IpAddressNotFound */ public function fetch(): ?string { @@ -104,8 +104,13 @@ public static function get(): ?string return $fetcher::isSupported(); }); - return (new static) - ->addFetchers($fetchers) - ->fetch(); + try { + return (new static) + ->addFetchers($fetchers) + ->fetch(); + } catch (Exception) { + // We ignore these exceptions, we want ::get() to be silent + return null; + } } }