Permalink
Browse files

重構 4 式 : Extract Closure

  • Loading branch information...
1 parent 82be134 commit c6071d37752b79c66d3c46d374696d196a131d4d Sam.IO.Hsiao committed Nov 27, 2016
Showing with 26 additions and 11 deletions.
  1. +15 −0 app/Services/AbstractLogistics.php
  2. +5 −5 app/Services/BlackCat.php
  3. +3 −3 app/Services/Hsinchu.php
  4. +3 −3 app/Services/Post.php
@@ -16,4 +16,19 @@ protected function arrayToCollection(array $weightArray): Collection
return $weights;
}
+
+ /**
+ * @param int $amount
+ * @param Collection $weights
+ * @param callable $closure
+ * @return int
+ */
+ protected function loopWeights(int $amount, Collection $weights, callable $closure): int
+ {
+ foreach ($weights as $weight) {
+ $amount = $amount + $closure($weight);
+ }
+
+ return $amount;
+ }
}
@@ -2,8 +2,6 @@
namespace App\Services;
-use Illuminate\Support\Collection;
-
class BlackCat extends AbstractLogistics
{
/**
@@ -15,10 +13,12 @@ public function calculateFee(array $weightArray, int $amount) : int
{
$weights = $this->arrayToCollection($weightArray);
- foreach ($weights as $weight) {
- $amount = $amount + (100 + $weight * 10);
- }
+ $amount = $this->loopWeights($amount, $weights, function (int $weight) {
+ return (100 + $weight * 10);
+ });
return $amount;
}
+
+
}
@@ -13,9 +13,9 @@ public function calculateFee(array $weightArray, int $amount) : int
{
$weights = $this->arrayToCollection($weightArray);
- foreach ($weights as $weight) {
- $amount = $amount + (80 + $weight * 15);
- }
+ $amount = $this->loopWeights($amount, $weights, function (int $weight) {
+ return (80 + $weight * 15);
+ });
return $amount;
}
@@ -13,9 +13,9 @@ public function calculateFee(array $weightArray, int $amount) : int
{
$weights = $this->arrayToCollection($weightArray);
- foreach ($weights as $weight) {
- $amount = $amount + (60 + $weight * 20);
- }
+ $amount = $this->loopWeights($amount, $weights, function (int $weight) {
+ return (60 + $weight * 20);
+ });
return $amount;
}

0 comments on commit c6071d3

Please sign in to comment.