<?php

namespace Ignite\Core\Entities\Scopes;

use Ignite\Core\Contracts\Entities\Filters\QueryFilter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

/**
 * This is just a convenience class. It allows you to use QueryFilters as Global Scopes without having to create a
 * new global scope class.
 *
 * So, here's an example of how to add a global scope to a model:
 * https://laravel.com/docs/8.x/eloquent#applying-global-scopes
 * If you wanted to do that with this scope, that would just be:
 * static::addGlobalScope(new QueryFilterScope(new MyQueryFilter));
 */
class QueryFilterScope implements Scope
{
    /**
     * @var QueryFilter
     */
    private $queryFilter;

    public function __construct(QueryFilter $queryFilter)
    {
        $this->queryFilter = $queryFilter;
    }

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \Illuminate\Database\Eloquent\Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $this->queryFilter->assertForTable($model);
        $this->queryFilter->apply($builder);
    }
}
