Pipeline.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use Closure;
  13. use Exception;
  14. use Throwable;
  15. class Pipeline
  16. {
  17. protected $passable;
  18. protected $pipes = [];
  19. protected $exceptionHandler;
  20. /**
  21. * 初始数据
  22. * @param $passable
  23. * @return $this
  24. */
  25. public function send($passable)
  26. {
  27. $this->passable = $passable;
  28. return $this;
  29. }
  30. /**
  31. * 调用栈
  32. * @param $pipes
  33. * @return $this
  34. */
  35. public function through($pipes)
  36. {
  37. $this->pipes = is_array($pipes) ? $pipes : func_get_args();
  38. return $this;
  39. }
  40. /**
  41. * 执行
  42. * @param Closure $destination
  43. * @return mixed
  44. */
  45. public function then(Closure $destination)
  46. {
  47. $pipeline = array_reduce(
  48. array_reverse($this->pipes),
  49. $this->carry(),
  50. function ($passable) use ($destination) {
  51. try {
  52. return $destination($passable);
  53. } catch (Throwable | Exception $e) {
  54. return $this->handleException($passable, $e);
  55. }
  56. }
  57. );
  58. return $pipeline($this->passable);
  59. }
  60. /**
  61. * 设置异常处理器
  62. * @param callable $handler
  63. * @return $this
  64. */
  65. public function whenException($handler)
  66. {
  67. $this->exceptionHandler = $handler;
  68. return $this;
  69. }
  70. protected function carry()
  71. {
  72. return function ($stack, $pipe) {
  73. return function ($passable) use ($stack, $pipe) {
  74. try {
  75. return $pipe($passable, $stack);
  76. } catch (Throwable | Exception $e) {
  77. return $this->handleException($passable, $e);
  78. }
  79. };
  80. };
  81. }
  82. /**
  83. * 异常处理
  84. * @param $passable
  85. * @param $e
  86. * @return mixed
  87. */
  88. protected function handleException($passable, Throwable $e)
  89. {
  90. if ($this->exceptionHandler) {
  91. return call_user_func($this->exceptionHandler, $passable, $e);
  92. }
  93. throw $e;
  94. }
  95. }