Skip to content
Merged
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
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,19 @@ To get a `Sort` instance, you can use either `Sort::only()` or `Sort::any()`. `S
for logical fields that have no configuration. `Sort::any()` uses user-specified logical field name and order directly
for fields that have no configuration.

Either way, you pass a config array that specifies which logical fields should be order-able and, optionally, details on
how these should map to real fields order.
Use `Sort::only()` by default, especially when the order comes from user input. Define the allowed logical fields in
application code:

```php
$sort = Sort::only(['id', 'name'])->withOrderString($userInput);
```

`Sort::any()` does not restrict sorting to the configured fields or validate unknown field names. Before passing
untrusted input to `withOrder()` or `withOrderString()` on a `Sort::any()` instance, validate the field names against
the fields your application allows. Passing unchecked field names to a database-backed reader can lead to SQL injection.

In both modes, the config array defines logical fields and, optionally, how they map to real fields and their order.
Only `Sort::only()` restricts sorting to those configured logical fields.

The current order to apply is specified via `withOrder()` where you supply an array with keys corresponding to logical
field names and values correspond to order (`asc` or `desc`). Alternatively `withOrderString()` can be used. In this case,
Expand Down
16 changes: 14 additions & 2 deletions docs/guide/pt-BR/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,20 @@ Para obter uma instância `Sort`, você pode usar `Sort::only()` ou `Sort::any()
para campos lógicos que não possuem configuração. `Sort::any()` usa o nome do campo lógico especificado pelo usuário e ordena diretamente
para campos que não possuem configuração.

De qualquer forma, você passa um array de configuração que especifica quais campos lógicos devem ser ordenados e, opcionalmente, detalhes sobre
como eles devem ser mapeados para a ordem real dos campos.
Use `Sort::only()` por padrão, especialmente quando a ordenação vier de dados fornecidos pelo usuário. Defina os campos
lógicos permitidos no código da aplicação:

```php
$sort = Sort::only(['id', 'name'])->withOrderString($userInput);
```

`Sort::any()` não restringe a ordenação aos campos configurados nem valida nomes de campos desconhecidos. Antes de passar
dados não confiáveis para `withOrder()` ou `withOrderString()` em uma instância de `Sort::any()`, valide os nomes dos campos
de acordo com os campos permitidos pela aplicação. Passar nomes de campos sem validação para um leitor que consulta um
banco de dados pode levar à injeção de SQL.

Nos dois modos, o array de configuração define os campos lógicos e, opcionalmente, como eles são mapeados para os campos
reais e sua ordenação. Apenas `Sort::only()` restringe a ordenação aos campos lógicos configurados.

A ordem atual a ser aplicada é especificada via `withOrder()` onde você fornece um array com chaves lógicas correspondentes
aos nomes e valores dos campos correspondem à ordem (`asc` ou `desc`). Alternativamente `withOrderString()` pode ser usado. Nesse caso
Expand Down
10 changes: 10 additions & 0 deletions src/Reader/Sort.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
* - {@see Sort::only()} ignores user-specified order for logical fields that have no configuration.
* - {@see Sort::any()} uses user-specified logical field name and order directly for fields that have no configuration.
*
* Use {@see Sort::only()} by default, especially for user input. With {@see Sort::any()}, validate untrusted field names
* against the fields your application allows before setting the order. Unchecked field names can lead to SQL injection
* when used with a database-backed reader.
*
* @psalm-type TOrder = array<string, "asc"|"desc">
* @psalm-type TSortFieldItem = array<string, int>
* @psalm-type TConfigItem = array{asc: TSortFieldItem, desc: TSortFieldItem, default: "asc"|"desc"}
Expand Down Expand Up @@ -131,6 +135,8 @@ private function __construct(private bool $ignoreExtraFields, array $config)
/**
* Create a sort instance that ignores the current order for extra logical fields that have no configuration.
*
* Recommended by default, especially for user input. Define the allowed logical fields in application code.
*
* @param array $config Logical fields config.
* @psalm-param TUserConfig $config
*
Expand Down Expand Up @@ -173,6 +179,10 @@ public static function only(array $config): self
/**
* Create a sort instance that uses logical field itself and direction provided when there is no configuration.
*
* The configuration is not an allowlist. Before passing untrusted input to {@see withOrder()} or
* {@see withOrderString()}, validate field names against the fields your application allows. Unchecked field names
* can lead to SQL injection when used with a database-backed reader. Prefer {@see only()} for user input.
*
* @param array $config Logical fields config.
* @psalm-param TUserConfig $config
*
Expand Down
Loading