4 * This file is part of the webmozart/path-util package.
6 * (c) Bernhard Schussek <bschussek@gmail.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Webmozart\PathUtil;
14 use InvalidArgumentException;
15 use Webmozart\Assert\Assert;
18 * Contains utility methods for handling URL strings.
20 * The methods in this class are able to deal with URLs.
24 * @author Bernhard Schussek <bschussek@gmail.com>
25 * @author Claudio Zizza <claudio@budgegeria.de>
30 * Turns a URL into a relative path.
32 * The result is a canonical path. This class is using functionality of Path class.
36 * @param string $url A URL to make relative.
37 * @param string $baseUrl A base URL.
41 * @throws InvalidArgumentException If the URL and base URL does
44 public static function makeRelative($url, $baseUrl)
46 Assert::string($url, 'The URL must be a string. Got: %s');
47 Assert::string($baseUrl, 'The base URL must be a string. Got: %s');
48 Assert::contains($baseUrl, '://', '%s is not an absolute Url.');
50 list($baseHost, $basePath) = self::split($baseUrl);
52 if (false === strpos($url, '://')) {
53 if (0 === strpos($url, '/')) {
60 list($host, $path) = self::split($url);
63 if ('' !== $host && $host !== $baseHost) {
64 throw new InvalidArgumentException(sprintf(
65 'The URL "%s" cannot be made relative to "%s" since their host names are different.',
71 return Path::makeRelative($path, $basePath);
75 * Splits a URL into its host and the path.
78 * list ($root, $path) = Path::split("http://example.com/webmozart")
79 * // => array("http://example.com", "/webmozart")
81 * list ($root, $path) = Path::split("http://example.com")
82 * // => array("http://example.com", "")
85 * @param string $url The URL to split.
87 * @return string[] An array with the host and the path of the URL.
89 * @throws InvalidArgumentException If $url is not a URL.
91 private static function split($url)
93 $pos = strpos($url, '://');
94 $scheme = substr($url, 0, $pos + 3);
95 $url = substr($url, $pos + 3);
97 if (false !== ($pos = strpos($url, '/'))) {
98 $host = substr($url, 0, $pos);
99 $url = substr($url, $pos);
101 // No path, only host
106 // At this point, we have $scheme, $host and $path
107 $root = $scheme.$host;
109 return array($root, $url);