From fd788a7eb804b7fe085346d817123c04c8bd0d01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=B8=9C=E4=BA=91?= Date: Wed, 19 Jul 2023 15:52:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(trait):=20=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=E5=88=86=E9=A1=B5=E5=93=8D=E5=BA=94=E7=9A=84=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=A4=84=E7=90=86=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李东云 --- src/Traits/PaginatorAble.php | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/Traits/PaginatorAble.php diff --git a/src/Traits/PaginatorAble.php b/src/Traits/PaginatorAble.php new file mode 100644 index 0000000..6cbe82a --- /dev/null +++ b/src/Traits/PaginatorAble.php @@ -0,0 +1,45 @@ + + * Powered by PhpStorm + * Created on 2023/7/18 + */ + +namespace Singularity\HDK\Core\Traits; + +use Closure; +use Hyperf\Contract\LengthAwarePaginatorInterface; +use Hyperf\Database\Model\Builder; +use Hyperf\Stringable\Str; + +trait PaginatorAble +{ + public function responseFormatter( + array $options, + Builder $builder, + ?Closure $filter = null + ) { + $perPage = $options['size'] ?? null; + $order = $options['order'] ?? 'created_at'; + $sort = $options['sort'] ?? 'desc'; + $pagination = !!($options['page'] ?? $perPage ?? false); + // $group = $options['group'] ?? null; + + $builder = $builder->orderBy(Str::snake($order), $sort); + $result = $pagination ? $builder->paginate($perPage) : $builder->get(); + + if (is_null($filter)) { + return $result; + } + + if ($result instanceof LengthAwarePaginatorInterface) { + $collection = $result->getCollection(); + $collection = $filter($collection); + + return $result->setCollection($collection); + } + return $filter($result); + } +} \ No newline at end of file