Skip to content

Commit

Permalink
Merge pull request #11 from wmde/euro_string_casting
Browse files Browse the repository at this point in the history
Add string casting / JSON serialization to Euro class
  • Loading branch information
timEulitz committed May 3, 2019
2 parents 0fc91f2 + 3f0a21e commit 58020c9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
3 changes: 2 additions & 1 deletion composer.json
Expand Up @@ -4,7 +4,8 @@
"homepage": "https://github.com/wmde/Euro",
"license": "GPL-2.0-or-later",
"require": {
"php": ">=7.1"
"php": ">=7.1",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "~6.2",
Expand Down
16 changes: 15 additions & 1 deletion src/Euro.php
Expand Up @@ -10,7 +10,7 @@
* @licence GNU GPL v2+
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
final class Euro {
final class Euro implements \JsonSerializable {

private const DECIMAL_COUNT = 2;
private const CENTS_PER_EURO = 100;
Expand All @@ -29,6 +29,20 @@ private function __construct( int $cents ) {
$this->cents = $cents;
}

/**
* @return string
*/
public function __toString(): string {
return $this->getEuroString();
}

/**
* @return string
*/
public function jsonSerialize(): string {
return $this->getEuroString();
}

/**
* @param int $cents
* @return self
Expand Down
10 changes: 10 additions & 0 deletions tests/Unit/EuroTest.php
Expand Up @@ -91,6 +91,16 @@ public function testGiven1234Cents_getEuroStringReturns12euro34() {
$this->assertSame( '12.34', $amount->getEuroString() );
}

public function testGiven9876Cents_stringCastingReturns98euro76() {
$amount = Euro::newFromCents( 9876 );
$this->assertSame( '98.76', (string) $amount );
}

public function testGivenEuroAmount_jsonEncodeWillEncodeProperly() {
$amount = Euro::newFromCents( 9876 );
$this->assertSame( '"98.76"', json_encode( $amount ) );
}

public function testOneEuroString_getsTurnedInto100cents() {
$this->assertSame( 100, Euro::newFromString( '1.00' )->getEuroCents() );
}
Expand Down

0 comments on commit 58020c9

Please sign in to comment.