<?php

namespace common\helpers;

use yii\data\ArrayDataProvider;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\db\Query;

class PaginationHelper
{
    /**
     * @param Query $query
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function queryPage(Query $query, $page = 1, $pageSize = 20)
    {
        $pagination = new Pagination();
        $pagination->totalCount = $query->count();
        $pagination->setPageSize($pageSize);
        $pagination->setPage($page - 1, true);
        if ($query instanceof ActiveQuery) {
            $query->asArray();
        }
        $models = $query->offset($pagination->getOffset())->limit($pagination->getLimit())->all();
        $dataProvider = new ArrayDataProvider([
            'models' => $models,
            'pagination' => $pagination,
        ]);
        return [
            'dataList' => $dataProvider->getModels(),
            'totalCount' => $dataProvider->getPagination()->totalCount,
            'pageCount' => $dataProvider->getPagination()->getPageCount(),
        ];
    }
}
