<?php

namespace LaravelDoctrine\ORM\Pagination;

use Doctrine\ORM\AbstractQuery;

trait PaginatesFromRequest
{
    /**
     * @param int    $perPage
     * @param string $pageName
     *
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function paginateAll($perPage = 15, $pageName = 'page')
    {
        $query = $this->createQueryBuilder('o')->getQuery();

        return $this->paginate($query, $perPage, $pageName, false);
    }

    /**
     * @param AbstractQuery $query
     * @param int           $perPage
     * @param bool          $fetchJoinCollection
     * @param string        $pageName
     *
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function paginate(AbstractQuery $query, $perPage, $pageName = 'page', $fetchJoinCollection = true)
    {
        return PaginatorAdapter::fromRequest(
            $query,
            $perPage,
            $pageName,
            $fetchJoinCollection
        )->make();
    }

    /**
     * Creates a new QueryBuilder instance that is prepopulated for this entity name.
     *
     * @param string $alias
     * @param string $indexBy The index for the from.
     *
     * @return \Doctrine\ORM\QueryBuilder
     */
    abstract public function createQueryBuilder($alias, $indexBy = null);
}
