Condition.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Form;
  4. /**
  5. * @mixin Form
  6. */
  7. class Condition
  8. {
  9. /**
  10. * @var Form
  11. */
  12. protected $form;
  13. protected $done = false;
  14. protected $condition;
  15. protected $result;
  16. /**
  17. * @var \Closure[]
  18. */
  19. protected $next = [];
  20. public function __construct($condition, Form $form)
  21. {
  22. $this->condition = $condition;
  23. $this->form = $form;
  24. }
  25. public function then(\Closure $closure)
  26. {
  27. $this->next[] = $closure;
  28. return $this;
  29. }
  30. public function now(\Closure $next = null)
  31. {
  32. $this->process($next);
  33. }
  34. public function else(\Closure $next = null)
  35. {
  36. $self = $this;
  37. $condition = $this->form->if(function () use ($self) {
  38. return ! $self->getResult();
  39. });
  40. if ($next) {
  41. $condition->then($next);
  42. }
  43. return $condition;
  44. }
  45. public function process(\Closure $next = null)
  46. {
  47. if ($this->done) {
  48. return;
  49. }
  50. $this->done = true;
  51. if (! $this->is()) {
  52. return;
  53. }
  54. if ($next) {
  55. $this->then($next);
  56. }
  57. foreach ($this->next as $callback) {
  58. $this->call($callback);
  59. }
  60. }
  61. public function is()
  62. {
  63. if ($this->condition instanceof \Closure) {
  64. $this->condition = $this->call($this->condition);
  65. }
  66. return $this->result = $this->condition ? true : false;
  67. }
  68. public function getResult()
  69. {
  70. return $this->result;
  71. }
  72. protected function call(\Closure $callback)
  73. {
  74. return $callback($this->form);
  75. }
  76. public function __call($name, $arguments)
  77. {
  78. if ($name == 'if') {
  79. return $this->form->if(...$arguments);
  80. }
  81. return $this->then(function (Form $form) use ($name, &$arguments) {
  82. return $form->$name(...$arguments);
  83. });
  84. }
  85. }