Condition.php 2.4 KB

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