Pipeline.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 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. return $pipeline($this->passable);
  58. }
  59. /**
  60. * 设置异常处理器
  61. * @param callable $handler
  62. * @return $this
  63. */
  64. public function whenException($handler)
  65. {
  66. $this->exceptionHandler = $handler;
  67. return $this;
  68. }
  69. protected function carry()
  70. {
  71. return function ($stack, $pipe) {
  72. return function ($passable) use ($stack, $pipe) {
  73. try {
  74. return $pipe($passable, $stack);
  75. } catch (Throwable | Exception $e) {
  76. return $this->handleException($passable, $e);
  77. }
  78. };
  79. };
  80. }
  81. /**
  82. * 异常处理
  83. * @param $passable
  84. * @param $e
  85. * @return mixed
  86. */
  87. protected function handleException($passable, Throwable $e)
  88. {
  89. if ($this->exceptionHandler) {
  90. return call_user_func($this->exceptionHandler, $passable, $e);
  91. }
  92. throw $e;
  93. }
  94. }