Skip to content

Commit

Permalink
add FormatterServiceInterface
Browse files Browse the repository at this point in the history
  • Loading branch information
rez1dent3 committed Jan 5, 2024
1 parent 873bbc2 commit 9d2fdc2
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Services/FormatterService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Services;

use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;

final readonly class FormatterService implements FormatterServiceInterface
{
public function intValue(string|int|float $amount, int $decimalPlaces): string
{
return (string) BigDecimal::ten()
->power($decimalPlaces)
->multipliedBy(BigDecimal::of($amount))
->toScale(0, RoundingMode::DOWN);
}

public function floatValue(string|int|float $amount, int $decimalPlaces): string
{
return (string) BigDecimal::ofUnscaledValue($amount, $decimalPlaces);
}
}
15 changes: 15 additions & 0 deletions src/Services/FormatterServiceInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Services;

/**
* @internal
*/
interface FormatterServiceInterface
{
public function intValue(string|int|float $amount, int $decimalPlaces): string;

public function floatValue(string|int|float $amount, int $decimalPlaces): string;
}
55 changes: 55 additions & 0 deletions tests/Units/Service/FormatterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Test\Units\Service;

use Bavix\Wallet\Internal\Exceptions\ExceptionInterface;
use Bavix\Wallet\Services\FormatterServiceInterface;
use Bavix\Wallet\Test\Infra\TestCase;

/**
* @internal
*/
final class FormatterTest extends TestCase
{
/**
* @throws ExceptionInterface
*/
public function testFloatValueDP3(): void
{
$result = app(FormatterServiceInterface::class)->floatValue('12345', 3);

self::assertSame('12.345', $result);
}

/**
* @throws ExceptionInterface
*/
public function testFloatValueDP2(): void
{
$result = app(FormatterServiceInterface::class)->floatValue('12345', 2);

self::assertSame('123.45', $result);
}

/**
* @throws ExceptionInterface
*/
public function testIntValueDP3(): void
{
$result = app(FormatterServiceInterface::class)->intValue('12.345', 3);

self::assertSame('12345', $result);
}

/**
* @throws ExceptionInterface
*/
public function testIntValueDP2(): void
{
$result = app(FormatterServiceInterface::class)->intValue('123.45', 2);

self::assertSame('12345', $result);
}
}

0 comments on commit 9d2fdc2

Please sign in to comment.