activeQuery = $activeQuery; } /** * @return void */ public function clean(): void { unset($this->activeQuery, $this->_callback, $this->_group); $this->_offset = 0; $this->_limit = 100; $this->_max = 0; $this->_length = 0;; } /** * recover class by clone */ public function __clone() { $this->clean(); } /** * @param array|Closure $callback * @throws */ public function setCallback(array|Closure $callback): void { if (!is_callable($callback, true)) { throw new Exception('非法回调函数~'); } $this->_callback = $callback; } /** * @param int $number * @return Pagination */ public function setOffset(int $number): static { if ($number < 0) { $number = 0; } $this->_offset = $number; return $this; } /** * @param int $number * @return Pagination */ public function setLimit(int $number): static { if ($number < 1) { $number = 100; } else if ($number > 5000) { $number = 5000; } $this->_limit = $number; return $this; } /** * @param int $number * @return Pagination */ public function setMax(int $number): static { if ($number < 0) { return $this; } $this->_max = $number; return $this; } /** * @param array $param * @return void * @throws */ public function plunk(array $param = []): void { $this->loop($param); } /** * 轮训 * @param $param * @return array * @throws */ public function loop($param): array { if ($this->_max > 0 && $this->_length >= $this->_max) { return $this->output(); } [$length, $data] = $this->get(); try { call_user_func($this->_callback, $data, $param); } catch (\Throwable $exception) { error($exception); } finally { $data = null; } if ($length < $this->_limit) { return $this->output(); } return $this->loop($param); } /** * @return array */ public function output(): array { return []; } /** * @param $data * @param $param * @throws */ private function executed($data, $param): void { try { call_user_func($this->_callback, $data, $param); } catch (\Throwable $exception) { error($exception); } } /** * @return array|Collection * @throws */ private function get(): Collection|array { if ($this->_max > 0 && $this->_length + $this->_limit > $this->_max) { $this->_limit = $this->_length + $this->_limit - $this->_max; } $data = $this->activeQuery->offset($this->_offset)->limit($this->_limit)->get(); $this->_offset += $this->_limit; $size = $data->size(); $this->_length += $size; return [$size, $data]; } }