<?php

namespace Velis\Policy;

use User\User;
use Velis\App;

trait PolicyTrait
{
    /**
     * Returns Plain Old PHP Object with can* methods to handle authorization
     */
    abstract protected function getPolicy();

    public function __call($name, $arguments)
    {
        if (substr($name, 0, 3) === 'can' && method_exists($this->getPolicy(), $name)) {
            $arguments ??= [];

            if (empty($arguments) || !$arguments[0] instanceof User) {
                array_unshift($arguments, App::$user);
            }

            return $this->getPolicy()->$name(...$arguments);
        }

        return parent::__call($name, $arguments);
    }
}
