Skip to content

Commit

Permalink
fix: get() should not throw exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
SRWieZ committed Nov 24, 2024
1 parent c8561ae commit 2b937ac
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand Down
2 changes: 2 additions & 0 deletions examples/ipv6.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
15 changes: 10 additions & 5 deletions src/Abstracts/Finder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -53,8 +54,7 @@ public static function with(?FetcherContract $provider = null): static
}

/**
* @throws IpAddressNotFound
* @throws NoFetcherSpecified
* @throws NoFetcherSpecified|UnmatchedIpVersionReceived|IpAddressNotFound
*/
public function fetch(): ?string
{
Expand Down Expand Up @@ -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;
}
}
}

0 comments on commit 2b937ac

Please sign in to comment.