PricePipeTrait.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: blank
  5. * Date: 2022/4/12
  6. * Time: 14:03
  7. */
  8. namespace app\frontend\modules\dispatch\freight;
  9. trait PricePipeTrait
  10. {
  11. /**
  12. * @var Collection
  13. */
  14. public $priceCache;
  15. /**
  16. * @var Collection
  17. */
  18. private $pricePipes;
  19. /**
  20. * @return Collection
  21. */
  22. public function getPricePipes()
  23. {
  24. if (!isset($this->pricePipes)) {
  25. $this->pricePipes = $this->_getPricePipes();
  26. }
  27. return $this->pricePipes;
  28. }
  29. public function pushPipe($pipe)
  30. {
  31. $this->getPricePipes()->push($pipe);
  32. }
  33. public function _getPricePipes()
  34. {
  35. return collect([]);
  36. }
  37. /**
  38. * 获取某个节点之后的价格
  39. * @param $key
  40. * @return mixed
  41. * @throws AppException
  42. */
  43. public function getPriceAfter($key)
  44. {
  45. if (!isset($this->priceCache[$key])) {
  46. // 找到对应的节点
  47. $priceNode = $this->getPricePipes()->first(function (PriceNode $priceNode) use ($key) {
  48. return $priceNode->getKey() == $key;
  49. });
  50. if (!$priceNode) {
  51. throw new AppException("不存在的价格节点{$key}");
  52. }
  53. $this->priceCache[$key] = $priceNode->getPrice();
  54. }
  55. return $this->priceCache[$key];
  56. }
  57. }