Alternative for PHP function parse_url()

Today I was fixing a deprecation warning from PHP code sniffer about the use of the PHP standard function parse_url()

PHPCS: The use of function parse_url() is forbidden; use drop in instead

The recommended function UrlHelper::parse() is not very helpful in this use-case. I could not find a drop-in replacement for this function and did not want to write my own. So I was looking at Guzzle because that library must parse a URL somewhere and it does. Guzzle provides a PSR7 Utility class with a module to parse a URL string called Util::uriFor(). This function returns a Uri object which you can ask for the URL components you need.

I refactored the following code:

$scheme = parse_url($restEndpoint, PHP_URL_SCHEME);
$host = parse_url($restEndpoint, PHP_URL_HOST);

to this (simplified version):

use GuzzleHttp\Psr7\Utils;


$baseUriParts = Utils::uriFor($restEndpoint);
$scheme = $baseUriParts->getScheme();
$host = $baseUriParts->getHost();

I am using Drupal so Guzzle is already part of my project. If you do not yet have the Guzzle PSR7 utilities installed you can install them via composer:

composer require guzzlehttp/psr7