Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bpolaszek committed Nov 9, 2017
0 parents commit 9bb2779
Show file tree
Hide file tree
Showing 15 changed files with 1,168 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
vendor
composer.lock
32 changes: 32 additions & 0 deletions .scrutinizer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
filter:
excluded_paths: [tests/*]
checks:
php:
code_rating: true
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
tools:
php_analyzer: true
php_code_coverage: false
php_code_sniffer:
config:
standard: PSR2
filter:
paths: ['src']
php_loc:
enabled: true
excluded_dirs: [vendor, tests]
php_cpd:
enabled: true
excluded_dirs: [vendor, tests]
19 changes: 19 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
dist: xenial

language: php

php:
- 7.1
- 7.2

before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev

script:
- ./vendor/bin/phpcs --standard=psr2 -n src/
- mkdir -p build/logs
- ./vendor/bin/phpunit --coverage-clover build/logs/clover.xml

after_script:
- php vendor/bin/coveralls -v
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Benoit POLASZEK

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.
192 changes: 192 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
[![Latest Stable Version](https://poser.pugx.org/bentools/querystring/v/stable)](https://packagist.org/packages/bentools/querystring)
[![License](https://poser.pugx.org/bentools/querystring/license)](https://packagist.org/packages/bentools/querystring)
[![Build Status](https://img.shields.io/travis/bpolaszek/querystring/master.svg?style=flat-square)](https://travis-ci.org/bpolaszek/querystring)
[![Coverage Status](https://coveralls.io/repos/github/bpolaszek/querystring/badge.svg?branch=master)](https://coveralls.io/github/bpolaszek/querystring?branch=master)
[![Quality Score](https://img.shields.io/scrutinizer/g/bpolaszek/querystring.svg?style=flat-square)](https://scrutinizer-ci.com/g/bpolaszek/querystring)
[![Total Downloads](https://poser.pugx.org/bentools/querystring/downloads)](https://packagist.org/packages/bentools/querystring)

# QueryString

A PSR-7 compliant query string manipulator, with no dependency.

## Why?

Because I needed an intuitive way to add or remove parameters from a query string.

Oh, and, I also wanted that `['foos' => ['foo', 'bar']]` resolved to `foos[]=foo&foos[]=bar` instead of `foos[0]=foo&foos[1]=bar`, unlike many libraries do.

This behavior is not the default one of that library, but there's an [easy way to change it](#change-encoder).

## Usage


**Instanciation**

You can create a `QueryString` object from a string or an array of values.

```php
require_once __DIR__ . '/vendor/autoload.php';

use function BenTools\QueryString\query_string;

// Create from a Psr\Http\Message\UriInterface object
$qs = query_string($uri);

// Create from a string
$qs = query_string('foo=bar&baz=bat');

// Create from an array
$qs = query_string(['foo' => 'bar', 'baz' => 'bat']);

// Or create an empty object to get started
$qs = query_string();
```

If you don't like shortcut functions, use the class' factory:
```php
use BenTools\QueryString\QueryString;
$qs = QueryString::factory('foo=bar&baz=bat'); // Same argument requirements
```

**Retrieve all parameters**
```php
print_r($qs->getParams());
/* Array
(
[foo] => bar
[baz] => bat
) */
```

**Retrieve specific parameter**
```php
print_r($qs->getParam('foo')); // bar
```

**Add / replace parameter**
```php
$qs = $qs->withParam('foo', 'foofoo');
print_r($qs->getParams());
/* Array
(
[foo] => foofoo
[baz] => bat
) */
print($qs); // foo=foofoo&baz=bat
```

**Remove parameter**
```php
$qs = $qs->withoutParam('baz');
print($qs); // foo=foofoo
```

**Create from a complex, nested array**
```php
$qs = query_string([
'yummy' => [
'fruits' => [
'strawberries',
'apples',
'raspberries',
],
]
]);
```
**Retrieve a parameter at a specific path**
```php
print($qs->getParam('yummy', 'fruits', 2)); // raspberries
```


**Remove a parameter at a specific path**

_Example: remove "apples", resolved at `$params['yummy']['fruits'][1]`_

```php
$qs = $qs->withoutParam('yummy', 'fruits', 1);
print_r($qs->getParams());
/* Array
(
[yummy] => Array
(
[fruits] => Array
(
[0] => strawberries
[1] => raspberries
)

)

)*/
```

**Render as string**
```php
print(urldecode((string) $qs)); // yummy[fruits][0]=strawberries&yummy[fruits][1]=raspberries
```
_Hint: you can easily remove numeric indices by [switching to another encoder](#change-encoder)._

**Change encoding**
```php
$qs = query_string('param=foo bar');
print((string) $qs); // param=foo%20bar
$qs = $qs->withEncoding(PHP_QUERY_RFC1738);
print((string) $qs); // param=foo+bar
```

**Change separator**
```php
$qs = query_string('foo=bar&baz=bat');
$qs = $qs->withSeparator(';');
print((string) $qs); // foo=bar;baz=bat
```

**Instanciate from current location**

It will read `$_SERVER['QUERY_STRING']`.

```php
use function BenTools\QueryString\query_string;
$qs = query_string()->withCurrentLocation();
```
or:
```php
use BenTools\QueryString\QueryString;
$qs = QueryString::createFromCurrentLocation();
```

Of course this will throw a `RuntimeException` when trying to run this from `cli` :smile:

## Change encoder

Remove numeric indices:
```php
use BenTools\QueryString\Encoder\ArrayValuesNormalizerEncoder;
$qs = $qs->withEncoder(new ArrayValuesNormalizerEncoder());
print(urldecode((string) $qs)); // yummy[fruits][]=strawberries&yummy[fruits][]=raspberries
```

## PSR-7 manipulation
Example:

```php
use function BenTools\QueryString\query_string;

/**
* @var \Psr\Http\Message\MessageInterface $uri
*/
$uri = $uri->withQuery(
(string) query_string($uri->getQuery())->withParam('foo', 'bar')
);
```

## Installation
PHP 7.1+ is required.
> composer require bentools/querystring
## Tests
> ./vendor/bin/phpunit
## License
MIT
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "bentools/querystring",
"description": "PSR-7 Query String manipulation. PHP 7.1+",
"keywords": ["url", "uri", "query string", "psr-7", "psr7"],
"type": "library",
"license": "MIT",
"require": {
"php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "@stable",
"squizlabs/php_codesniffer": "@stable",
"satooshi/php-coveralls": "@stable",
"symfony/var-dumper": "^3.3",
"league/uri": "^5.0"
},
"autoload": {
"psr-4": {
"BenTools\\QueryString\\": "src"
},
"files": [
"src/functions.php"
]
},
"autoload-dev": {
"psr-4": {
"BenTools\\QueryString\\Tests\\": "tests"
},
"files": [
"vendor/symfony/var-dumper/Resources/functions/dump.php"
]
},
"config": {
"sort-packages": true
}
}
27 changes: 27 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutOutputDuringTests="true"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
failOnRisky="true"
failOnWarning="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
verbose="true"
>
<testsuite>
<directory suffix="Test.php">tests</directory>
</testsuite>

<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
33 changes: 33 additions & 0 deletions src/Encoder/ArrayValuesNormalizerEncoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace BenTools\QueryString\Encoder;

use BenTools\QueryString\QueryString;

final class ArrayValuesNormalizerEncoder implements QueryStringEncoderInterface
{
/**
* @var NativeEncoder
*/
private $nativeEncoder;

/**
* ArrayValuesStringifier constructor.
*/
public function __construct()
{
$this->nativeEncoder = new NativeEncoder();
}

/**
* @inheritDoc
*/
public function encode(QueryString $queryString): string
{
return preg_replace(
'/\%5B\d+\%5D/',
'%5B%5D',
$this->nativeEncoder->encode($queryString)
);
}
}
21 changes: 21 additions & 0 deletions src/Encoder/NativeEncoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace BenTools\QueryString\Encoder;

use BenTools\QueryString\QueryString;

final class NativeEncoder implements QueryStringEncoderInterface
{
/**
* @inheritDoc
*/
public function encode(QueryString $queryString): string
{
return http_build_query(
$queryString->getParams(),
null,
$queryString->getSeparator() ?? ini_get('arg_separator.output'),
$queryString->getEncoding()
);
}
}

0 comments on commit 9bb2779

Please sign in to comment.