Skip to content
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

Enhancement: Implement FormatSniffer #12

Merged
merged 2 commits into from
Jan 12, 2018
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
4 changes: 3 additions & 1 deletion .php_cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ the LICENSE file that was distributed with this source code.
@see https://github.com/localheinz/json-normalizer
EOF;

$config = Config\Factory::fromRuleSet(new Config\RuleSet\Php70($header));
$config = Config\Factory::fromRuleSet(new Config\RuleSet\Php70($header), [
'mb_str_functions' => false,
]);

$config->getFinder()->in(__DIR__);

Expand Down
66 changes: 66 additions & 0 deletions src/Format/FormatSniffer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

/**
* Copyright (c) 2018 Andreas Möller.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/localheinz/json-normalizer
*/

namespace Localheinz\Json\Normalizer\Format;

final class FormatSniffer implements FormatSnifferInterface
{
public function sniff(string $json): FormatInterface
{
if (null === \json_decode($json) && JSON_ERROR_NONE !== \json_last_error()) {
throw new \InvalidArgumentException(\sprintf(
'"%s" is not valid JSON.',
$json
));
}

return new Format(
$this->jsonEncodeOptions($json),
$this->indent($json),
$this->hasFinalNewLine($json)
);
}

private function jsonEncodeOptions(string $json): int
{
$jsonEncodeOptions = 0;

if (false === \strpos($json, '\/')) {
$jsonEncodeOptions |= JSON_UNESCAPED_SLASHES;
}

if (1 !== \preg_match('/(\\\\+)u([0-9a-f]{4})/i', $json)) {
$jsonEncodeOptions |= JSON_UNESCAPED_UNICODE;
}

return $jsonEncodeOptions;
}

private function indent(string $json): string
{
if (1 === \preg_match('/^(?P<indent>[ \t]+)("|{)/m', $json, $match)) {
return $match['indent'];
}

return ' ';
}

private function hasFinalNewLine(string $json): bool
{
if (\rtrim($json, " \t") === \rtrim($json)) {
return false;
}

return true;
}
}
26 changes: 26 additions & 0 deletions src/Format/FormatSnifferInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

/**
* Copyright (c) 2018 Andreas Möller.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/localheinz/json-normalizer
*/

namespace Localheinz\Json\Normalizer\Format;

interface FormatSnifferInterface
{
/**
* @param string $json
*
* @throws \InvalidArgumentException
*
* @return FormatInterface
*/
public function sniff(string $json): FormatInterface;
}
286 changes: 286 additions & 0 deletions test/Unit/Format/FormatSnifferTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
<?php

declare(strict_types=1);

/**
* Copyright (c) 2018 Andreas Möller.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/localheinz/json-normalizer
*/

namespace Localheinz\Json\Normalizer\Test\Unit\Format;

use Localheinz\Json\Normalizer\Format\FormatInterface;
use Localheinz\Json\Normalizer\Format\FormatSniffer;
use Localheinz\Json\Normalizer\Format\FormatSnifferInterface;
use Localheinz\Test\Util\Helper;
use PHPUnit\Framework;

final class FormatSnifferTest extends Framework\TestCase
{
use Helper;

public function testImplementsSnifferInterface()
{
$this->assertClassImplementsInterface(FormatSnifferInterface::class, FormatSniffer::class);
}

public function testSniffRejectsInvalidJson()
{
$json = $this->faker()->realText();

$sniffer = new FormatSniffer();

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(\sprintf(
'"%s" is not valid JSON.',
$json
));

$sniffer->sniff($json);
}

/**
* @dataProvider providerJsonAndJsonEncodeOptions
*
* @param int $jsonEncodeOptions
* @param string $json
*/
public function testSniffReturnsFormatWithJsonEncodeOptions(int $jsonEncodeOptions, string $json)
{
$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertSame($jsonEncodeOptions, $format->jsonEncodeOptions());
}

public function providerJsonAndJsonEncodeOptions(): array
{
return [
[
0,
'{
"name": "Andreas M\u00f6ller",
"url": "https:\/\/github.com\/localheinz\/json-normalizer"
}',
],
[
JSON_UNESCAPED_SLASHES,
'{
"name": "Andreas M\u00f6ller",
"url": "https://github.com/localheinz/json-normalizer"
}',
],
[
JSON_UNESCAPED_UNICODE,
'{
"name": "Andreas Möller",
"url": "https:\/\/github.com\/localheinz\/json-normalizer"
}',
],
[
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
'{
"name": "Andreas Möller",
"url": "https://github.com/localheinz/json-normalizer"
}',
],
];
}

/**
* @dataProvider providerJsonWithoutWhitespace
*
* @param string $json
*/
public function testSniffReturnsFormatWithDefaultIndentIfUnableToSniff(string $json)
{
$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertSame(' ', $format->indent());
}

public function providerJsonWithoutWhitespace(): \Generator
{
$values = [
'array-empty' => '[]',
'object-empty' => '{}',
'array-without-indent' => '["foo","bar baz"]',
'object-without-indent' => '{"foo":"bar baz","baz":[9000,123]}',
];

foreach ($values as $key => $value) {
yield $key => [
$value,
];
}
}

/**
* @dataProvider providerIndent
*
* @param string $indent
*/
public function testSniffReturnsFormatWithIndentSniffedFromArray(string $indent)
{
$json = <<<JSON
[
"foo",
${indent}"bar",
{
"qux": "quux"
}
]
JSON;

$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertSame($indent, $format->indent());
}

/**
* @dataProvider providerIndent
*
* @param string $indent
*/
public function testSniffReturnsFormatWithIndentIndentSniffedFromObject(string $indent)
{
$json = <<<JSON
{
"foo": 9000,
${indent}"bar": 123,
"baz": {
"qux": "quux"
}
}
JSON;

$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertSame($indent, $format->indent());
}

public function providerIndent(): \Generator
{
$characters = [
' ',
"\t",
];

$counts = [1, 3];

foreach ($characters as $character) {
foreach ($counts as $count) {
$indent = \str_repeat($character, $count);

yield [
$indent,
];
}
}
}

/**
* @dataProvider providerWhitespaceWithoutNewLine
*
* @param string $actualWhitespace
*/
public function testSniffReturnsFormatWithoutFinalNewLineIfThereIsNoFinalNewLine(string $actualWhitespace)
{
$json = <<<'JSON'
{
"foo": 9000,
"bar": 123,
"baz": {
"qux": "quux"
}
}
JSON;
$json .= $actualWhitespace;

$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertFalse($format->hasFinalNewLine());
}

public function providerWhitespaceWithoutNewLine(): \Generator
{
$characters = [
' ',
"\t",
];

foreach ($characters as $one) {
foreach ($characters as $two) {
$whitespace = $one . $two;

yield [
$whitespace,
];
}
}
}

/**
* @dataProvider providerWhitespaceWithNewLine
*
* @param string $actualWhitespace
*/
public function testSniffReturnsFormatWithFinalNewLineIfThereIsAtLeastOneFinalNewLine(string $actualWhitespace)
{
$json = <<<'JSON'
{
"foo": 9000,
"bar": 123,
"baz": {
"qux": "quux"
}
}
JSON;
$json .= $actualWhitespace;

$sniffer = new FormatSniffer();

$format = $sniffer->sniff($json);

$this->assertInstanceOf(FormatInterface::class, $format);
$this->assertTrue($format->hasFinalNewLine());
}

public function providerWhitespaceWithNewLine(): \Generator
{
$characters = [
'',
' ',
"\t",
PHP_EOL,
];

foreach ($characters as $before) {
foreach ($characters as $after) {
$whitespace = $before . PHP_EOL . $after;

yield [
$whitespace,
];
}
}
}
}