Skip to content

Commit

Permalink
Port Java to PHP with Hamcrest.
Browse files Browse the repository at this point in the history
  • Loading branch information
codecop committed Oct 17, 2019
1 parent 46506e2 commit ef77408
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 0 deletions.
49 changes: 49 additions & 0 deletions php/src/PromotionService/PromotionService.php
@@ -0,0 +1,49 @@
<?php
namespace PromotionService;

class Item
{
public $name;
public $price;
public $tax;

public function __construct($name, $price, $tax)
{
$this->name = $name;
$this->price = $price;
$this->tax = $tax;
}
}

class PromotionService
{

public function applyPromotionTo(Item $item)
{
$result = [];
$result[] = new UserMessage(sprintf("Total before promotion: %.1F", $item->price + $item->price * $item->tax));

$item->price -= $this->standardDiscount();
if ($item->price > 122) {
$item->tax /= 2;
}

$this->persist($item);

$result[] = new UserMessage(sprintf("Total after promotion: %.1F", $item->price + $item->price * $item->tax));
return $result;
}

// This method can't be moved to another class, used by other code in this class.
private function standardDiscount()
{
return 2;
}

private function persist(Item $item)
{
// Item is persisted to storage.
}

// ... There is more code in this class.
}
24 changes: 24 additions & 0 deletions php/src/PromotionService/UserMessage.php
@@ -0,0 +1,24 @@
<?php
namespace PromotionService;

class UserMessage
{

private $value;

public function __construct($value)
{
$this->value = $value;
}

public function getValue()
{
return $this->value;
}

public function __toString()
{
return $this->value;
}

}
33 changes: 33 additions & 0 deletions php/test/PromotionService/PromotionServiceTest.php
@@ -0,0 +1,33 @@
<?php
namespace PromotionService;

class PromotionServiceTest extends \PHPUnit_Framework_TestCase
{

/** @test */
public function bookPromotion()
{
$promotionService = new PromotionService();
$messages = $promotionService->applyPromotionTo(
new Item("Functional programming with C++", 10, 0.2));

assertThat($messages, equalTo([
new UserMessage("Total before promotion: 12.0"),
new UserMessage("Total after promotion: 9.6"),
]));
}

/** @test */
public function expensiveBookPromotion()
{
$promotionService = new PromotionService();
$messages = $promotionService->applyPromotionTo(
new Item("Functional programming with all languages", 210, 0.2));

assertThat($messages, equalTo([
new UserMessage("Total before promotion: 252.0"),
new UserMessage("Total after promotion: 228.8"),
]));
}

}

0 comments on commit ef77408

Please sign in to comment.