Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 153
RoleService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 11
1482.00
0.00% covered (danger)
0.00%
0 / 147
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 __clone
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 getInstance
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 5
 createRole
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 25
 updateRole
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 18
 deleteRole
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 20
 getAllActiveRoles
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 20
 getRole
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getUserRoles
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 18
 getRolesAccordingToRoleType
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getRoleByCode
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
<?php
namespace com\linways\core\ams\professional\service;
use com\linways\base\exception\CoreException;
use com\linways\base\util\MakeSingletonTrait;
use com\linways\common\api\exception\CommonApiException;
use com\linways\core\ams\professional\constant\SettingsConstants;
use com\linways\core\ams\professional\exception\ProfessionalException;
use com\linways\core\ams\professional\mapper\RoleServiceMapper;
use com\linways\core\ams\professional\request\CreateRoleRequest;
use com\linways\core\ams\professional\request\DeleteRoleRequest;
use com\linways\core\ams\professional\request\DeleteUserRolesByRoleRequest;
use com\linways\core\ams\professional\request\UpdateRoleRequest;
/**
 *
 * @Date 30/07/20
 * @author  JithinVijayan <jithin@linways.com>
 */
class RoleService extends BaseService
{
    /**
     * @var null
     */
    private static $_instance = null;
    /**
     * @var array
     */
    private $mapper = [];
    /**
     * RoleService constructor.
     */
    private function __construct()
    {
        $this->mapper = RoleServiceMapper::getInstance()->getMapper();
    }
    // ROLE CONST
    const ROLE_FACULTY = "FACULTY_DEFAULT";
    const ROLE_STUDENTS = "STUDENT_DEFAULT";
    const ROLE_PARENT = "PARENT_DEFAULT";
    // USER TYPES
    const USER_TYPE_STUDENT = "STUDENT";
    const USER_TYPE_STAFF = "STAFF";
    const USER_TYPE_PARENT = "PARENT";
    /**
     * Preventing cloning
     */
    private function __clone()
    {
    }
    /**
     * @return RoleService|null
     */
    public static function getInstance()
    {
        if (!is_object(self::$_instance))
            self::$_instance = new self();
        return self::$_instance;
    }
    /**
     * @param CreateRoleRequest $request
     * @return Object|integer
     * @throws ProfessionalException
     */
    public function createRole(CreateRoleRequest $request)
    {
        $request = $this->realEscapeObject($request);
        if (empty($request->name)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_NAME, "Invalid role name");
        }
        if (empty($request->code)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_CODE, "Invalid role code");
        }
        if (empty($request->properties)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_CODE, "Invalid role properties");
        }
        $request->properties->haveDepartmentRestriction = $request->properties->haveDepartmentRestriction === "1" ? true : false;
        $properties = !empty($request->properties) ? "'".json_encode($request->properties)."'" : "NULL";
        $sql = "INSERT INTO roles (name, code, userType, description, dynamic_modules_id, properties, created_by, created_date, updated_by, updated_date) 
                VALUES ('$request->name','$request->code', '$request->userType', '$request->description',".($request->dynamicModuleId?"'$request->dynamicModuleId'":'null')."$properties,$request->createdBy,UTC_TIMESTAMP(),
                $request->updatedBy,UTC_TIMESTAMP())";
        try {
            return $this->executeQueryForObject($sql, true);
        } catch (\Exception $e) {
            if ($e->getCode() === CoreException::DUPLICATE_ENTRY) {
                throw new ProfessionalException($e->getCode(), "This role has been taken. Please try another one");
            }
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param UpdateRoleRequest $request
     * @throws ProfessionalException
     */
    public function updateRole(UpdateRoleRequest $request)
    {
        $request = $this->realEscapeObject($request);
        if (empty($request->id)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_ID, "Invalid role details given");
        }
        if (empty($request->name)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_NAME, "Invalid role name");
        }
//        Once role was generated, it cannot be change because role code will be stored in cache so changing role code
//        if (empty($request->code)) {
//            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_CODE, "Invalid role code");
//        }
        $sql = "UPDATE roles 
                SET name='$request->name', description='$request->description', userType='$request->userType',
                updated_by='$request->updatedBy', updated_date=UTC_TIMESTAMP()
                WHERE id = $request->id";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param DeleteRoleRequest $request
     * @throws ProfessionalException
     */
    public function deleteRole(DeleteRoleRequest $request)
    {
        $request = $this->realEscapeObject($request);
        if (empty($request->id)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_ID, "Invalid role details given");
        }
        $sql = "DELETE FROM roles WHERE id = $request->id";
        try {
            $deleteRequest = new DeleteUserRolesByRoleRequest();
            $deleteRequest->roleId = $request->id;
            $deleteRequest->createdBy = $request->createdBy;
            $deleteRequest->updatedBy = $request->updatedBy;
            $this->beginTransaction();
            UserRoleService::getInstance()->deleteUserRolesByRoleId($deleteRequest);
            $this->executeQuery($sql);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollBack();
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @return Object
     * @throws ProfessionalException
     */
    public function getAllActiveRoles()
    {
        try {
            global $GLOBALS;
            $sql = "SELECT id,name,userType,code,description FROM roles WHERE is_active  =1 ";
            if($GLOBALS['dynamicModuleId']){
                $sql .=" AND dynamic_modules_id='".$GLOBALS['dynamicModuleId']."' ";
            }
            else{
                $sql .="AND dynamic_modules_id is null";
            }
            $roles = $this->executeQueryForList($sql, $this->mapper[RoleServiceMapper::GET_ACTIVE_ROLES]);
            $defaultRoles = json_decode(CommonService::getInstance()->getSettings(SettingsConstants::V4_PRODUCT_CONFIGURATION, SettingsConstants::V4_DEFINED_ROLES));
            $d = array_map(function($r) {return $r->const;},$defaultRoles);
            foreach ($roles as $key => $role) {
                $role->isDefaultRole = in_array($role->code, $d) ? true : false;
            }
            return $roles;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $roleId
     * @return Object
     * @throws ProfessionalException
     */
    public function getRole($roleId)
    {
        $roleId = (int)$this->realEscapeString($roleId);
        if (empty($roleId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_ID, "Invalid role details given");
        }
        $sql = "SELECT id,code,name,description FROM roles WHERE id  =$roleId";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param INT $userId
     * @param String $userType
     * @return Object
     * @throws ProfessionalException
     */
    public function getUserRoles($userId,$userType){
        $userId = (int)$this->realEscapeString($userId);
        $userType = $this->realEscapeString($userType);
        if (empty($userId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_ID, "Invalid user details given");
        }
        if (empty($userType)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_TYPE, "Invalid user details given");
        }
        $sql = "SELECT r.id,r.code,r.name,r.description FROM roles r 
                INNER JOIN user_account_roles uar ON uar.role_id = r.id 
                WHERE uar.user_id = '$userId' AND uar.user_type = '$userType'
                GROUP BY r.id;";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param Array $roleTypes
     * @return Object
     * @throws ProfessionalException
     */
    public function getRolesAccordingToRoleType($roleTypes){
        $roleTypes = $this->realEscapeArray($roleTypes);
        if (empty($roleTypes)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_TYPES, "Invalid role details given");
        }
        $sql = "SELECT r.id,r.code,r.name,r.description FROM roles r 
                WHERE r.userType IN ('".implode("','",$roleTypes)."');";
        try {
            return $this->executeQueryForList($sql);
     
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $roleId
     * @return Object
     * @throws ProfessionalException
     */
    public function getRoleByCode($code)
    {
        $code = $this->realEscapeString($code);
        if (empty($code)) {
            throw new ProfessionalException(ProfessionalException::INVALID_ROLE_ID, "Invalid code details given");
        }
        $sql = "SELECT id,code,name,description FROM roles WHERE code = '$code';";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
}