Condition.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 then(\Closure $closure)
  22. {
  23. $this->next[] = $closure;
  24. return $this;
  25. }
  26. public function now(\Closure $next = null)
  27. {
  28. $this->process($next);
  29. }
  30. public function process(\Closure $next = null)
  31. {
  32. if ($this->done) {
  33. return;
  34. }
  35. $this->done = true;
  36. if (! $this->is()) {
  37. return;
  38. }
  39. if ($next) {
  40. $this->then($next);
  41. }
  42. foreach ($this->next as $callback) {
  43. $this->call($callback);
  44. }
  45. }
  46. public function is()
  47. {
  48. if ($this->condition instanceof \Closure) {
  49. $this->condition = $this->call($this->condition);
  50. }
  51. return $this->condition ? true : false;
  52. }
  53. protected function call(\Closure $callback)
  54. {
  55. return $callback($this->form);
  56. }
  57. public function __call($name, $arguments)
  58. {
  59. if (! method_exists($this->form, $name)) {
  60. return $this;
  61. }
  62. return $this->then(function (Form $form) use ($name, &$arguments) {
  63. return $form->$name(...$arguments);
  64. });
  65. }
  66. }