Condition.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php
  2. namespace Dcat\Admin\Grid\Column;
  3. use Dcat\Admin\Grid\Column;
  4. /**
  5. * @mixin Column
  6. */
  7. class Condition
  8. {
  9. /**
  10. * @var Column
  11. */
  12. protected $original;
  13. /**
  14. * @var Column
  15. */
  16. protected $column;
  17. /**
  18. * @var mixed
  19. */
  20. protected $condition;
  21. /**
  22. * @var bool
  23. */
  24. protected $result;
  25. /**
  26. * @var \Closure[]
  27. */
  28. protected $next = [];
  29. public function __construct($condition, Column $column)
  30. {
  31. $this->condition = $condition;
  32. $this->original = clone $column;
  33. $this->column = $column;
  34. }
  35. public function then(\Closure $closure)
  36. {
  37. $this->next[] = $closure;
  38. return $this;
  39. }
  40. public function else(\Closure $next = null)
  41. {
  42. $self = $this;
  43. $condition = $this->column->if(function () use ($self) {
  44. return ! $self->getResult();
  45. });
  46. if ($next) {
  47. $condition->then($next);
  48. }
  49. return $condition;
  50. }
  51. public function process()
  52. {
  53. if ($this->is()) {
  54. $this->callCallbacks($this->next);
  55. }
  56. }
  57. protected function callCallbacks(array $callbacks)
  58. {
  59. if (! $callbacks) {
  60. return;
  61. }
  62. $column = $this->copy();
  63. foreach ($callbacks as $callback) {
  64. $this->call($callback, $column);
  65. }
  66. $this->setColumnDisplayers($column->getDisplayCallbacks());
  67. }
  68. public function reset()
  69. {
  70. $this->setColumnDisplayers($this->original->getDisplayCallbacks());
  71. }
  72. public function setColumnDisplayers(array $callbacks)
  73. {
  74. $this->column->setDisplayCallbacks($callbacks);
  75. }
  76. protected function copy()
  77. {
  78. return clone $this->original;
  79. }
  80. public function is()
  81. {
  82. $condition = $this->condition;
  83. if ($condition instanceof \Closure) {
  84. $condition = $this->call($condition);
  85. }
  86. return $this->result = $condition ? true : false;
  87. }
  88. public function getResult()
  89. {
  90. return $this->result;
  91. }
  92. protected function call(\Closure $callback, $column = null)
  93. {
  94. $column = $column ?: $this->column;
  95. return $callback->call($this->column->getOriginalModel(), $column);
  96. }
  97. public function __call($name, $arguments)
  98. {
  99. if ($name == 'if') {
  100. return $this->column->if(...$arguments);
  101. }
  102. return $this->then(function ($column) use ($name, &$arguments) {
  103. return $column->$name(...$arguments);
  104. });
  105. }
  106. }