GoodsMemberLevelDiscount.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2018/12/29
  6. * Time: 11:40 AM
  7. */
  8. namespace app\common\modules\discount;
  9. use app\common\models\Goods;
  10. use app\common\models\Member;
  11. /**
  12. * 商品会员等级优惠计算类
  13. * Class GoodsMemberLevelDiscount
  14. * @package app\common\modules\discount
  15. */
  16. class GoodsMemberLevelDiscount
  17. {
  18. private $goods;
  19. private $member;
  20. public function __construct(Goods $goods, Member $member)
  21. {
  22. $this->goods = $goods;
  23. $this->member = $member;
  24. }
  25. /**
  26. * 计算者
  27. * @return BaseGoodsMemberLevelDiscountCalculator
  28. */
  29. private function getDiscountCalculator($price)
  30. {
  31. // 从配置文件中载入,按优先级排序 遍历取到第一个通过验证的 计算者
  32. $calculatorConfigs = collect(\app\common\modules\shop\ShopConfig::current()->get('shop-foundation.discount.GoodsMemberLevelDiscountCalculator'))->sortBy('priority');
  33. // 返回第一个通过验证的计算者
  34. foreach ($calculatorConfigs as $calculatorConfig) {
  35. /**
  36. * @var BaseGoodsMemberLevelDiscountCalculator $calculator
  37. */
  38. $calculator = call_user_func($calculatorConfig['class'], $this->goods, $this->member);
  39. if ($calculator->validate($price)) {
  40. // 通过验证返回
  41. return $calculator;
  42. }
  43. }
  44. // 默认计算者
  45. return new NoneGoodsMemberLevelDiscountCalculator($this->goods, $this->member);
  46. }
  47. /**
  48. * @param $price
  49. * @return float
  50. */
  51. public function getAmount($price)
  52. {
  53. return $this->getDiscountCalculator($price)->getAmount($price);
  54. }
  55. public function getLog($amount)
  56. {
  57. return $this->getDiscountCalculator($amount)->getLog($amount);
  58. }
  59. }