Skip to content

[Uri] Add component #57192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
"symfony/twig-bundle": "self.version",
"symfony/type-info": "self.version",
"symfony/uid": "self.version",
"symfony/uri": "self.version",
"symfony/validator": "self.version",
"symfony/var-dumper": "self.version",
"symfony/var-exporter": "self.version",
Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/Uri/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
8 changes: 8 additions & 0 deletions src/Symfony/Component/Uri/.github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Please do not submit any Pull Requests here. They will be closed.
---

Please submit your PR here instead:
https://github.com/symfony/symfony

This repository is what we call a "subtree split": a read-only subset of that main repository.
We're looking forward to your PR there!
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Check subtree split

on:
pull_request_target:

jobs:
close-pull-request:
runs-on: ubuntu-latest

steps:
- name: Close pull request
uses: actions/github-script@v6
with:
script: |
if (context.repo.owner === "symfony") {
github.rest.issues.createComment({
owner: "symfony",
repo: context.repo.repo,
issue_number: context.issue.number,
body: `
Thanks for your Pull Request! We love contributions.

However, you should instead open your PR on the main repository:
https://github.com/symfony/symfony

This repository is what we call a "subtree split": a read-only subset of that main repository.
We're looking forward to your PR there!
`
});

github.rest.pulls.update({
owner: "symfony",
repo: context.repo.repo,
pull_number: context.issue.number,
state: "closed"
});
}
3 changes: 3 additions & 0 deletions src/Symfony/Component/Uri/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions src/Symfony/Component/Uri/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.2
---

* Add the component as experimental
20 changes: 20 additions & 0 deletions src/Symfony/Component/Uri/Exception/InvalidUriException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Uri\Exception;

final class InvalidUriException extends \RuntimeException
{
public function __construct(string $uri)
{
parent::__construct(sprintf('The URI "%s" is invalid.', $uri));
}
}
20 changes: 20 additions & 0 deletions src/Symfony/Component/Uri/Exception/UnresolvableUriException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Uri\Exception;

final class UnresolvableUriException extends \RuntimeException
{
public function __construct(string $uri)
{
parent::__construct(sprintf('The URI "%s" cannot be used as a base URI in a resolution.', $uri));
}
}
46 changes: 46 additions & 0 deletions src/Symfony/Component/Uri/FragmentTextDirective.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Uri;

/**
* As defined in the Scroll to Text Fragment proposal.
*
* @see https://wicg.github.io/scroll-to-text-fragment/
*
* @experimental
*
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
final class FragmentTextDirective implements \Stringable
{
public function __construct(
public string $start,
public ?string $end = null,
public ?string $prefix = null,
public ?string $suffix = null,
) {
}

/**
* Dash, comma and ampersand are encoded, @see https://wicg.github.io/scroll-to-text-fragment/#syntax.
*/
public function __toString(): string
{
$encode = static fn (string $value) => strtr($value, ['-' => '%2D', ',' => '%2C', '&' => '%26']);

return ':~:text='
.($this->prefix ? $encode($this->prefix).'-,' : '')
.$encode($this->start)
.($this->end ? ','.$encode($this->end) : '')
.($this->suffix ? ',-'.$encode($this->suffix) : '');
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Uri/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
184 changes: 184 additions & 0 deletions src/Symfony/Component/Uri/QueryString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Uri;

/**
* @experimental
*
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
final class QueryString implements \Stringable
{
/**
* @var array<string, string|string[]>
*/
private array $parameters = [];

/**
* Parses a URI.
*
* Unlike `parse_str()`, this method does not overwrite duplicate keys but instead
* returns an array of all values for each key:
*
* QueryString::parse('foo=1&foo=2&bar=3'); // stored as ['foo' => ['1', '2'], 'bar' => '3']
*
* `+` are supported in parameter keys and not replaced by an underscore:
*
* QueryString::parse('foo+bar=1'); // stored as ['foo bar' => '1']
*
* `.` and `_` are supported distinct in parameter keys:
*
* QueryString::parse('foo.bar=1'); // stored as ['foo.bar' => '1']
* QueryString::parse('foo_bar=1'); // stored as ['foo_bar' => '1']
*/
public static function parse(string $query): self
{
$parts = explode('&', $query);
$queryString = new self();

foreach ($parts as $part) {
if ('' === $part) {
continue;
}

$part = explode('=', $part, 2);
$key = urldecode($part[0]);
// keys without value will be stored as empty strings, as "parse_str()" does
$value = isset($part[1]) ? urldecode($part[1]) : '';

// take care of nested arrays
if (preg_match_all('/\[(.*?)]/', $key, $matches)) {
$nestedKeys = $matches[1];
// nest the value inside the extracted keys
$value = array_reduce(array_reverse($nestedKeys), static function ($carry, $key) {
return [$key => $carry];
}, $value);

$key = strstr($key, '[', true);
}

if ($queryString->has($key)) {
$queryString->set($key, self::deepMerge((array) $queryString->get($key), (array) $value));
} else {
$queryString->set($key, $value);
}
}

return $queryString;
}

public function has(string $key): bool
{
return \array_key_exists($key, $this->parameters);
}

/**
* Get the first value of the first tuple whose name is `$key`.
*
* @see https://url.spec.whatwg.org/#interface-urlsearchparams
*
* @return string|string[]|null
*/
public function get(string $key): string|array|null
{
$param = $this->parameters[$key] ?? null;

if (\is_array($param) && array_is_list($param)) {
return $param[0];
}

return $param;
}

/**
* Get all values of the tuple whose name is `$key`.
*
* @see https://url.spec.whatwg.org/#interface-urlsearchparams
*
* @return string|string[]|null
*/
public function getAll(string $key): string|array|null
{
return $this->parameters[$key] ?? null;
}

public function set(string $key, array|string|null $value): self
{
$this->parameters[$key] = $value;

return $this;
}

public function remove(string $key): self
{
unset($this->parameters[$key]);

return $this;
}

/**
* @return array<string, string|string[]>
*/
public function all(): array
{
return $this->parameters;
}

public function __toString(): string
Copy link

@nyamsprod nyamsprod Jun 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the expected returned value for this snippet ?

<?php

echo QueryString::parse('foo[bar]=1&foo[bar]=2'), PHP_EOL;
  • foo[bar]=1&foo[bar]=2
  • or foo[bar]=2
  • or foo[bar]=1

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not find an explicit explanation in the RFC about how to handle arrays in query strings. I went for the first solution, as demonstrated in the tests here: https://github.com/symfony/symfony/compare/4b37a248e96e13835678a8ae405931b3eb51af89..85eee4361f6e26db5a0fa26e5ddd13e3412228ae#diff-50079d0a06175c27cec11386ec6b7b0249844bdb99b036169ddb5ad49dc6ca03

{
$parts = [];
foreach (self::flattenParameters($this->parameters) as $key => $values) {
foreach ((array) $values as $value) {
$parts[] = strtr($key, [' ' => '+']).'='.urlencode($value);
}
}

return implode('&', $parts);
}

private static function flattenParameters(array $parameters, string $prefix = ''): array
{
$result = [];
foreach ($parameters as $key => $value) {
$newKey = '' === $prefix ? $key : $prefix.'['.$key.']';

if (\is_array($value)) {
$result += self::flattenParameters($value, $newKey);
} else {
$result[$newKey] = $value;
}
}

return $result;
}

private static function deepMerge(array $parameters, array $newParameters): array
{
foreach ($newParameters as $key => $value) {
if (\is_array($value) && isset($parameters[$key]) && \is_array($parameters[$key])) {
$parameters[$key] = self::deepMerge($parameters[$key], $value);
} elseif (isset($parameters[$key])) {
$merge = array_merge((array) $parameters[$key], (array) $value);

if (\is_string($key)) {
$parameters[$key] = $merge;
} else {
$parameters = $merge;
}
} else {
$parameters[$key] = $value;
}
}

return $parameters;
}
}
Loading
Loading