Condition.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Form;
  4. class Condition
  5. {
  6. /**
  7. * @var Form
  8. */
  9. protected $form;
  10. protected $done = false;
  11. protected $condition;
  12. /**
  13. * @var \Closure[]
  14. */
  15. protected $next = [];
  16. public function __construct($condition, Form $form)
  17. {
  18. $this->condition = $condition;
  19. $this->form = $form;
  20. }
  21. public function next(\Closure $closure)
  22. {
  23. $this->next[] = $closure;
  24. return $this;
  25. }
  26. public function then(\Closure $next = null)
  27. {
  28. if ($this->done) {
  29. return;
  30. }
  31. $this->done = true;
  32. if (! $this->is()) {
  33. return;
  34. }
  35. if ($next) {
  36. $this->next($next);
  37. }
  38. foreach ($this->next as $callback) {
  39. $this->call($callback);
  40. }
  41. }
  42. public function is()
  43. {
  44. if ($this->condition instanceof \Closure) {
  45. $this->condition = $this->call($this->condition);
  46. }
  47. return $this->condition ? true : false;
  48. }
  49. protected function call(\Closure $callback)
  50. {
  51. return $callback($this->form);
  52. }
  53. public function __call($name, $arguments)
  54. {
  55. if (! method_exists($this->form, $name)) {
  56. return $this;
  57. }
  58. return $this->next(function (Form $form) use ($name, &$arguments) {
  59. return $form->$name(...$arguments);
  60. });
  61. }
  62. }