|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace BenTools\QueryString\Renderer; |
| 4 | + |
| 5 | +use BenTools\QueryString\QueryString; |
| 6 | + |
| 7 | +final class FlatRenderer implements QueryStringRendererInterface |
| 8 | +{ |
| 9 | + /** |
| 10 | + * @var NativeRenderer |
| 11 | + */ |
| 12 | + private $renderer; |
| 13 | + |
| 14 | + protected function __construct(QueryStringRendererInterface $renderer = null) |
| 15 | + { |
| 16 | + $this->renderer = $renderer; |
| 17 | + } |
| 18 | + |
| 19 | + public static function factory(QueryStringRendererInterface $renderer = null) |
| 20 | + { |
| 21 | + return new self($renderer ?? NativeRenderer::factory()); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * @inheritDoc |
| 26 | + */ |
| 27 | + public function render(QueryString $queryString): string |
| 28 | + { |
| 29 | + $separator = $this->getSeparator() ?? ini_get('arg_separator.output'); |
| 30 | + $parts = [[]]; |
| 31 | + |
| 32 | + foreach ($queryString->getParams() as $key => $value) { |
| 33 | + $parts[] = $this->getParts($key, $value); |
| 34 | + } |
| 35 | + |
| 36 | + return \implode($separator, \array_merge([], ...$parts)); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @inheritDoc |
| 41 | + */ |
| 42 | + public function getEncoding(): int |
| 43 | + { |
| 44 | + return $this->renderer->getEncoding(); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * @inheritDoc |
| 49 | + */ |
| 50 | + public function withEncoding(int $encoding): QueryStringRendererInterface |
| 51 | + { |
| 52 | + return new self($this->renderer->withEncoding($encoding)); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @inheritDoc |
| 57 | + */ |
| 58 | + public function getSeparator(): ?string |
| 59 | + { |
| 60 | + return $this->renderer->getSeparator(); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @inheritDoc |
| 65 | + */ |
| 66 | + public function withSeparator(?string $separator): QueryStringRendererInterface |
| 67 | + { |
| 68 | + return new self($this->renderer->withSeparator($separator)); |
| 69 | + } |
| 70 | + |
| 71 | + private function getParts($key, $value): array |
| 72 | + { |
| 73 | + if (\is_iterable($value)) { |
| 74 | + $parts = [[]]; |
| 75 | + foreach ($value as $sub) { |
| 76 | + $parts[] = $this->getParts($key, $sub); |
| 77 | + } |
| 78 | + |
| 79 | + return \array_merge([], ...$parts); |
| 80 | + } |
| 81 | + |
| 82 | + $encode = \PHP_QUERY_RFC1738 === $this->getEncoding() ? '\\urlencode' : '\\rawurlencode'; |
| 83 | + |
| 84 | + return [$key . '=' . \call_user_func($encode, $value)]; |
| 85 | + } |
| 86 | +} |
0 commit comments