Last active
April 5, 2021 11:39
-
-
Save szepeviktor/6b7d670d87164d1ced5c541bbf630eee to your computer and use it in GitHub Desktop.
Display parsed URL.
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
#!/usr/bin/php | |
<?php | |
/** | |
* Display parsed URL. | |
*/ | |
// Print the first command line arguments parsed. | |
(new URL($argv[1]))->print(); | |
class URL | |
{ | |
public const TAB_SIZE = 2; | |
protected string $url; | |
public function __construct(string $url) | |
{ | |
$this->url = $url; | |
} | |
/** | |
* @return array<string, mixed> | |
*/ | |
public function parse(string $url): array | |
{ | |
$parsedUrl = parse_url($url); | |
if ($parsedUrl === false) { | |
$parsedUrl = []; | |
} | |
// Parse query string. | |
if (array_key_exists('query', $parsedUrl)) { | |
$parsedQuery = []; | |
parse_str($parsedUrl['query'], $parsedQuery); | |
$parsedUrl['query'] = $parsedQuery; | |
} | |
return $parsedUrl; | |
} | |
public function print(): void | |
{ | |
echo $this->getArrayPrintout($this->parse($this->url)), PHP_EOL; | |
} | |
/** | |
* @param array<string, mixed> $array | |
* @return list<string> | |
*/ | |
public function convertArrayToLines(array $array, int $indent = 0): array | |
{ | |
$lines = []; | |
$increasedIndent = $indent + self::TAB_SIZE; | |
foreach ($array as $key => $value) { | |
if (is_int($value)) { | |
$lines[] = sprintf("%s%-8s %d", str_pad('', $increasedIndent), $key . ':', $value); | |
continue; | |
} | |
if (is_string($value)) { | |
$lines[] = sprintf("%s%-8s '%s'", str_pad('', $increasedIndent), $key . ':', $value); | |
continue; | |
} | |
if (is_array($value)) { | |
$lines[] = $this->getArrayPrintout($value, $key, $increasedIndent); | |
continue; | |
} | |
// Fallback. | |
$lines[] = str_pad('', $increasedIndent) . var_export([$key, $value], true); | |
} | |
return $lines; | |
} | |
/** | |
* @param array<string, mixed> $array | |
*/ | |
public function getArrayPrintout(array $array, string $name = 'url', int $indent = 0): string | |
{ | |
$padding = str_pad('', $indent); | |
return implode( | |
$padding . PHP_EOL, | |
array_merge( | |
[sprintf('%s%s(', $padding, $name)], | |
$this->convertArrayToLines($array, $indent), | |
[sprintf('%s)', $padding)] | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
See https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#basics_anatomy_of_a_url