From 9c0c15069de2c938b7943a7adc8a1a838700d621 Mon Sep 17 00:00:00 2001 From: Sebastian Lenz Date: Wed, 2 Dec 2020 22:40:50 +0100 Subject: [PATCH] Add url model class --- src/models/Url.php | 162 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 src/models/Url.php diff --git a/src/models/Url.php b/src/models/Url.php new file mode 100644 index 0000000..c591251 --- /dev/null +++ b/src/models/Url.php @@ -0,0 +1,162 @@ +attributes + [ + 'auth' => $this->getAuthentication(), + ]; + + foreach (self::GLUES as list($key, $prefix, $suffix)) { + $value = isset($parts[$key]) ? $parts[$key] : ''; + if (!empty($value)) { + array_push($result, $prefix, $value, $suffix); + } + } + + if (isset($parts['host']) && !isset($parts['scheme'])) { + array_unshift($result, '//'); + } + + return implode('', $result); + } + + /** + * @return string + */ + public function getAuthentication() { + return implode(':', array_filter([ + isset($this->user) ? $this->user : '', + isset($this->pass) ? $this->pass : '', + ])); + } + + /** + * @return string|null + */ + public function getFragment() { + return isset($this->fragment) ? (string)$this->fragment : null; + } + + /** + * @return array + */ + public function getQuery() { + if (!isset($this->query)) { + return []; + } + + $result = array(); + foreach (explode('&', $this->query) as $param) { + $parts = explode('=', $param, 2); + if (count($parts) !== 2) { + continue; + } + + list($key, $value) = $parts; + $result[$key] = urldecode($value); + } + + return $result; + } + + /** + * @param string|null $fragment + */ + public function setFragment(string $fragment = null) { + if (empty($fragment)) { + unset($this->fragment); + } else { + $this->fragment = $fragment; + } + } + + /** + * @param array $query + */ + public function setQuery(array $query) { + if (count($query) === 0) { + unset($this->query); + } else { + $parts = []; + foreach ($query as $key => $value) { + $parts[] = $key . '=' . urlencode($value); + } + + $this->query = implode('&', $parts); + } + } +}