Skip to content

Commit

Permalink
Add JSONCoercion to config (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Schneider authored Aug 15, 2019
1 parent e4661d6 commit 9dc7c14
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Config/JSONCoercion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Scoutapm\Config;

class JSONCoercion
{
public function coerce($value)
{
if (is_string($value)) {
// assoc=true to create an array instead of an object
return json_decode($value, true);
}

return $value;
}
}
53 changes: 53 additions & 0 deletions tests/Config/BoolCoercionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
namespace Scoutapm\Tests\Config;

use \PHPUnit\Framework\TestCase;
use \Scoutapm\Config\BoolCoercion;

/**
* Test Case for @see \Scoutapm\Config
*/
final class BoolCoercionTest extends TestCase
{
public function testParsesStrings()
{
$c = new BoolCoercion();

$this->assertEquals(true, $c->coerce('t'));
$this->assertEquals(true, $c->coerce('true'));
$this->assertEquals(true, $c->coerce('1'));
$this->assertEquals(true, $c->coerce('yes'));
$this->assertEquals(true, $c->coerce('YES'));
$this->assertEquals(true, $c->coerce('T'));
$this->assertEquals(true, $c->coerce('TRUE'));

// Falses
$this->assertEquals(false, $c->coerce('f'));
$this->assertEquals(false, $c->coerce('false'));
$this->assertEquals(false, $c->coerce('no'));
$this->assertEquals(false, $c->coerce('0'));
}

public function testIgnoresBooleans()
{
$c = new BoolCoercion();

$this->assertEquals(true, $c->coerce(true));
$this->assertEquals(false, $c->coerce(false));
}

public function testNullIsFalse()
{
$c = new BoolCoercion();

$this->assertEquals(false, $c->coerce(null));
}

public function testAnythingElseIsFalse()
{
$c = new BoolCoercion();

// $c is "any object"
$this->assertEquals(false, $c->coerce($c));
}
}
32 changes: 32 additions & 0 deletions tests/Config/JSONCoercionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
namespace Scoutapm\Tests\Config;

use \PHPUnit\Framework\TestCase;
use \Scoutapm\Config\JSONCoercion;

/**
* Test Case for @see \Scoutapm\Config
*/
final class JSONCoercionTest extends TestCase
{
public function testParsesJSON()
{
$c = new JSONCoercion();
$this->assertEquals([
"foo" => 1
], $c->coerce('{"foo": 1}'));
}

// Return null for any invalid JSON
public function testInvalidJSON()
{
$c = new JSONCoercion();
$this->assertEquals(null, $c->coerce('foo: 1}'));
}

public function testIgnoresNonString()
{
$c = new JSONCoercion();
$this->assertEquals(10, $c->coerce(10));
}
}

0 comments on commit 9dc7c14

Please sign in to comment.