Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active April 5, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szepeviktor/6b7d670d87164d1ced5c541bbf630eee to your computer and use it in GitHub Desktop.
Save szepeviktor/6b7d670d87164d1ced5c541bbf630eee to your computer and use it in GitHub Desktop.
Display parsed URL.
#!/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)]
)
);
}
}
@szepeviktor
Copy link
Author

szepeviktor commented Mar 6, 2021

Usage

$ ./url.php 'https://www.example.com:443/path/to/file.html?key1=value1&key2=value2#anchor'
url(
  scheme:  'https'
  host:    'www.example.com'
  port:    443
  path:    '/path/to/file.html'
  query(
    key1:    'value1'
    key2:    'value2'
  )
  fragment: 'anchor'
)

See https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#basics_anatomy_of_a_url

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment