<?php
namespace models;

/**
 * Role model
 * @author Jérôme Brilland
 * @version 3.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Role extends \ActiveRecord {

    const ADMINISTRATOR = 1;
    const REGISTERED_USER = 2;

    protected function validate() {
        $i18n = \IoC::resolve( 'i18n' );
        $this->validateMaxLength( 'name', 100, $i18n->__( 'too_long_name', 100 ) );
        $this->validateNotEmpty( 'name', $i18n->__( 'name_cannot_be_empty' ) );
        $this->validateUnique( 'name', $i18n->__( 'name_taken' ) );
    }

    protected function beforeSave() {
        $this->name = trim( $this->name );
        if ( !empty( $this->description ) ) {
            $this->description = ucfirst( $this->description );
        }
    }
    
    public static function findByName( $name ) {
        return self::findOne( ['name' => $name] );
    }
    
    public function hasPermission( $name ) {
        return PermissionRole::exists( ['[>]permission' => 'permission_id'], ['role_id' => $this->role_id, 'name' => $name] );
    }
    
    public function getPermissions() {
        return Permission::findMany( ['[>]permission_role' => 'permission_id'], ['name'], ['role_id' => $this->role_id] );
    }

    public function __toString() {
        return $this->name;
    }

}
