Skip to content

Commit 81c6fa9

Browse files
committed
refactor: implements chain of resposibility pattern in discount calculator
1 parent 50611ac commit 81c6fa9

5 files changed

+83
-7
lines changed

src/Discounts/Discount.php

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fbsouzas\DesignPattern\Discounts;
6+
7+
use Fbsouzas\DesignPattern\Budgets\Budget;
8+
9+
abstract class Discount
10+
{
11+
protected ?Discount $nextDiscount;
12+
13+
public function __construct(?Discount $nextDiscount)
14+
{
15+
$this->nextDiscount = $nextDiscount;
16+
}
17+
18+
abstract public function calculate(Budget $budget): float;
19+
}

src/Discounts/DiscountCalculator.php

+6-7
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,13 @@ class DiscountCalculator
1010
{
1111
public function calculate(Budget $budget): float
1212
{
13-
if ($budget->quantityOfItems > 5) {
14-
return $budget->value * 0.1;
15-
}
1613

17-
if ($budget->value > 500) {
18-
return $budget->value * 0.05;
19-
}
14+
$chainOfDiscount = new DiscountToMoreThan5Items(
15+
new DiscountToValueHigherThan500(
16+
new NoDiscount()
17+
)
18+
);
2019

21-
return 0;
20+
return $chainOfDiscount->calculate($budget);
2221
}
2322
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fbsouzas\DesignPattern\Discounts;
6+
7+
use Fbsouzas\DesignPattern\Budgets\Budget;
8+
9+
class DiscountToMoreThan5Items extends Discount
10+
{
11+
public function calculate(Budget $budget): float
12+
{
13+
if ($budget->quantityOfItems > 5) {
14+
return $budget->value * 0.1;
15+
}
16+
17+
return $this->nextDiscount->calculate($budget);
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fbsouzas\DesignPattern\Discounts;
6+
7+
use Fbsouzas\DesignPattern\Budgets\Budget;
8+
9+
class DiscountToValueHigherThan500 extends Discount
10+
{
11+
public function calculate(Budget $budget): float
12+
{
13+
if ($budget->value > 500) {
14+
return $budget->value * 0.05;
15+
}
16+
17+
return $this->nextDiscount->calculate($budget);
18+
}
19+
}

src/Discounts/NoDiscount.php

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Fbsouzas\DesignPattern\Discounts;
6+
7+
use Fbsouzas\DesignPattern\Budgets\Budget;
8+
9+
class NoDiscount extends Discount
10+
{
11+
public function __construct()
12+
{
13+
parent::__construct(null);
14+
}
15+
16+
public function calculate(Budget $budget): float
17+
{
18+
return 0;
19+
}
20+
}

0 commit comments

Comments
 (0)