<?php
namespace services\authorization;

use models\RolePermission;
/**
 * Permission assignation service
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class AssignRolePermissions {

    private $roleId;
    private $permissions;

    public function __construct( $roleId, array $permissions ) {
        $this->roleId = $roleId;
        $this->permissions = $permissions;
    }

    public function perform( $listener ) {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'assign_role_permissions' );
        
        $rolePermissions = RolePermission::findMany( '*', ['role_id' => $this->roleId] );
        foreach( $this->permissions as $permissionId => $isAssigned ) {
            if ( $isAssigned && ( !in_array( $permissionId, array_column( $rolePermissions, 'permission_id' ) ) ) ) {
                $rolePermission = new RolePermission();
                $rolePermission->role_id = $this->roleId;
                $rolePermission->permission_id = $permissionId;
                $rolePermission->save();
            } else if ( !$isAssigned && ( in_array( $permissionId, array_column( $rolePermissions, 'permission_id' ) ) ) ) {
                $rolePermission = array_column( $rolePermissions, NULL, 'permission_id' )[$permissionId];
                $rolePermission->delete();         
            }
        }
    }
}
