Created
January 10, 2022 12:29
-
-
Save stoll/572cacf674f864a24ab2f7eaff0bcf2e to your computer and use it in GitHub Desktop.
Url.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Url | |
{ | |
protected $scheme; // - e.g. http | |
protected $host; // | |
protected $port; // | |
protected $user; // | |
protected $pass; // | |
protected $path; // | |
protected $query = []; // - after the question mark ? | |
protected $fragment; // - after the hashmark # | |
public function __construct($url) | |
{ | |
if ( ! is_array($url)) { | |
$url = parse_url($url); | |
} | |
$this->scheme = data_get($url, 'scheme', null); | |
$this->host = data_get($url, 'host', null); | |
$this->port = data_get($url, 'port', null); | |
$this->user = data_get($url, 'user', null); | |
$this->pass = data_get($url, 'pass', null); | |
$this->path = data_get($url, 'path', null); | |
$this->setQuery(data_get($url, 'query', null)); | |
$this->fragment = data_get($url, 'fragment', null); | |
} | |
// setters | |
public function setQuery($query) | |
{ | |
if (is_string($query) && strlen($query) > 0) { | |
$this->query = collect(explode('&', $query)) | |
->filter(function ($queryPart) { | |
return count(explode('=', $queryPart, 2)) === 2; | |
}) | |
->mapWithKeys(function ($queryPart) { | |
$queryPart = explode('=', $queryPart, 2); | |
return [$queryPart[0] => $queryPart[1]]; | |
}) | |
->toArray(); | |
} elseif (is_array($query)) { | |
$this->query = $query; | |
} else { | |
$this->query = []; | |
} | |
return $this; | |
} | |
// methods | |
public function setQueryParam($key, $value) | |
{ | |
$this->query[$key] = $value; | |
return $this; | |
} | |
public function buildUrl() | |
{ | |
return parse_url_reverse([ | |
'scheme' => $this->scheme, | |
'host' => $this->host, | |
'port' => $this->port, | |
'user' => $this->user, | |
'pass' => $this->pass, | |
'path' => $this->path, | |
'query' => http_build_query($this->query), | |
'fragment' => $this->fragment, | |
]); | |
} | |
public function __toString() | |
{ | |
return $this->buildUrl(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment