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 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 267
RuleService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 14
4290.00
0.00% covered (danger)
0.00%
0 / 267
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 saveRule
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 25
 validateSaveRuleRequest
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 8
 insertRule
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 updateRule
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 15
 deleteRule
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 20
 restoreRule
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 19
 searchRule
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 40
 assignRule
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 25
 validateAssignRuleRequest
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 10
 insertRuleGroupRelation
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 updateRuleGroupRelation
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 16
 deleteRuleGroupRelation
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 16
 getAssignedRule
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 45
<?php
namespace com\linways\ec\core\service;
use com\linways\base\util\SecurityUtils;
use com\linways\ec\core\dto\Rule;
use com\linways\base\util\MakeSingletonTrait;
use com\linways\ec\core\constant\StatusConstants;
use com\linways\ec\core\exception\ExamControllerException;
use com\linways\ec\core\request\SearchRuleRequest;
use com\linways\ec\core\mapper\RuleServiceMapper;
class RuleService extends BaseService
{
    use MakeSingletonTrait;
    private function __construct() {
        $this->mapper = RuleServiceMapper::getInstance()->getMapper();
    }
    /**
     * Save rule
     * @param Rule $rule
     * @return String $id
     */
    public function saveRule (Rule $rule)
    {
        $rule = $this->realEscapeObject($rule);
        $rule->createdBy = $GLOBALS['userId'] ?? $rule->createdBy;
        $rule->updatedBy = $GLOBALS['userId'] ?? $rule->updatedBy;
        try{
            $this->validateSaveRuleRequest($rule);
            
            if(!empty($rule->id))
            {
                $rule->id = $this->updateRule($rule);
            }
            else
            {
                $rule->id = $this->insertRule($rule);
            }
        }catch(\Exception $e) {
            if($e->getCode() !== ExamControllerException::INVALID_PARAMETERS_RULE && $e->getCode() !== ExamControllerException::EMPTY_PARAMETERS_RULE && $e->getCode() !== ExamControllerException::DUPLICATE_ENTRY_RULE) {
                throw new ExamControllerException(ExamControllerException::ERROR_SAVING_RULE,"Failed to save rule! Please try again");
            } else if ($e->getCode() === ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException (ExamControllerException::DUPLICATE_ENTRY_RULE,"Cannot create rule.Rule already exists!");
            } else {
                throw new ExamControllerException ($e->getCode(),$e->getMessage());
            }
        }
        
        return $rule->id;
    }
    
    /**
     * Validate Rule Request Before Saving
     * @param Rule $rule
     * @return NULL
     */
    private function validateSaveRuleRequest(Rule $rule)
    {
        if(empty($rule->studentId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_RULE,"Rule is empty! Please select rule");
            
        if(empty($rule->assessmentId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_RULE,"Exam is invalid.");
        if((empty($rule->createdBy)  && empty($rule->id)) || (empty($rule->updatedBy) && !empty($rule->id)))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_RULE,"Unauthorized entry.");
    }
    
    /**
     * Insert rule
     * @param Rule $rule
     * @return String $id
     */
    private function insertRule(Rule $rule)
    {
        $ruleProperties = !empty($rule->rule) ? "'".json_encode($rule->rule)."'" : "JSON_OBJECT()";
        $id = SecurityUtils::getRandomString();
        $query = "INSERT INTO ec_rule
            (id,name,rule,created_by,updated_by)
        VALUES
            ('$id','$rule->name',$ruleProperties,'$rule->createdBy','$rule->updatedBy')";
        
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $id;
    }
    /**
     * Update Rule
     * @param Rule $rule
     * @return NULL
     */
    private function updateRule(Rule $rule)
    {
        $ruleProperties = !empty($rule->rule) ? "'".json_encode($rule->rule)."'" : "JSON_OBJECT()";
        
        $query = "UPDATE ec_rule 
        SET 
            name = '$rule->name',
            rule = $ruleProperties,
            updated_by = '$rule->updatedBy'
        WHERE 
            id = '$rule->id'";
        try {
            $this->executeQuery($query);return $rule->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete Rule (Soft Delete)
     * @param String $id
     * @return NULL
     */
    public function deleteRule($id)
    {
        $id = $this->realEscapeString($id);
        $updatedBy = $GLOBALS['userId'];
        if(empty($id)) {
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_RULE,"Rule not found. Please try again!");
        }
        $query = "UPDATE 
            ec_rule 
        SET 
            trashed = UTC_TIMESTAMP(),
            updated_by = '$updatedBy
        WHERE 
            id = '$id'";
        try {
            CommonService::getInstance()->checkForeignKeyEntries("ec_rule",$id);
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_DELETING_RULE,"Error deleting rule! Please try again");
        }
    }
    /**
     * Restore Rule
     * @param String $id
     * @return NULL
     */
    public function restoreRule($id)
    {
        $id = $this->realEscapeString($id);
        $updatedBy = $GLOBALS['userId'];
        if(empty($id)) {
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_RULE,"Rule not found. Please try again!");
        }
        $query = "UPDATE 
            ec_rule 
        SET 
            trashed=NULL,
            updated_by='$updatedBy
        WHERE 
            id='$id'";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_RESTORING_RULE,"Error restoring rule! Please try again");
        }
    }
    
    /**
     * Search Rule Details
     * @param SearchRuleRequest $request
     * @return Rule
     */
    public function searchRule(SearchRuleRequest $request)
    {
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        $limitQuery = "";
        if(!empty($request->id)) {
            $whereQuery .= " AND r.id='$request->id'";
        }
        if($request->trashed === StatusConstants::ACTIVE) {
            $whereQuery .= " AND r.trashed IS NULL";
        }
        if($request->trashed === StatusConstants::TRASHED) {
            $whereQuery .= " AND r.trashed IS NOT NULL";
        }
        if(!empty($request->name)) {
            $whereQuery .= " AND r.name LIKE '%$request->name%'";
        }
        if($request->startIndex !== "" && $request->endIndex !== "")
        {
            $limitQuery .= " LIMIT $request->startIndex,$request->endIndex";
        }
        $query = "SELECT
            r.id,
            r.name,
            r.rule,
            r.trashed,
            r.created_by,
            r.created_date,
            r.updated_by,
            r.updated_date
        FROM
            ec_rule r
        WHERE
            1 = 1";
        try {
            $rules = $this->executeQueryForList($query.$whereQuery.$limitQuery,$this->mapper[RuleServiceMapper::SEARCH_RULES]);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_RULE,"Cannot fetch rule details! Please try again");
        }
        return $rules;
    }
    /**
     * Assign rule
     * @param RuleGroupRelation $ruleGroupRelation
     * @return String $id
     */
    public function assignRule (RuleGroupRelation $ruleGroupRelation)
    {
        $ruleGroupRelation = $this->realEscapeObject($ruleGroupRelation);
        $ruleGroupRelation->createdBy = $GLOBALS['userId'] ?? $ruleGroupRelation->createdBy;
        $ruleGroupRelation->updatedBy = $GLOBALS['userId'] ?? $ruleGroupRelation->updatedBy;
        try{
            $this->validateAssignRuleRequest($ruleGroupRelation);
            
            if(!empty($ruleGroupRelation->id))
            {
                $ruleGroupRelation->id = $this->updateRuleGroupRelation($ruleGroupRelation);
            }
            else
            {
                $ruleGroupRelation->id = $this->insertRuleGroupRelation($ruleGroupRelation);
            }
        }catch(\Exception $e) {
            if($e->getCode() !== ExamControllerException::INVALID_PARAMETERS_ASSIGN_RULE && $e->getCode() !== ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE && $e->getCode() !== ExamControllerException::DUPLICATE_ENTRY_ASSIGN_RULE) {
                throw new ExamControllerException(ExamControllerException::ERROR_SAVING_ASSIGN_RULE,"Failed to assign rule! Please try again");
            } else if ($e->getCode() === ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException (ExamControllerException::DUPLICATE_ENTRY_ASSIGN_RULE,"Cannot assign rule. Rule already assigned!");
            } else {
                throw new ExamControllerException ($e->getCode(),$e->getMessage());
            }
        }
        
        return $ruleGroupRelation->id;
    }
    
    /**
     * Validate Assign Rule Request Before Saving
     * @param RuleGroupRelation $ruleGroupRelation
     * @return NULL
     */
    private function validateAssignRuleRequest(RuleGroupRelation $ruleGroupRelation)
    {
        if(empty($ruleGroupRelation->ruleId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE,"Rule is empty! Please select rule");
            
        if(empty($ruleGroupRelation->groupId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE,"Batch is empty! Please select batch.");
        if(empty($ruleGroupRelation->type))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE,"Rule type is Empty.");
        if((empty($ruleGroupRelation->createdBy)  && empty($ruleGroupRelation->id)) || (empty($ruleGroupRelation->updatedBy) && !empty($ruleGroupRelation->id)))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE,"Unauthorized entry.");
    }
    /**
     * Insert rule
     * @param RuleGroupRelation $ruleGroupRelation
     * @return String $id
     */
    private function insertRuleGroupRelation(RuleGroupRelation $ruleGroupRelation)
    {
        $query = "INSERT INTO ec_rule_group_relation
            (ec_rule_id,groups_id,type,created_by,updated_by)
        VALUES
            ('$ruleGroupRelation->ruleId','$ruleGroupRelation->groupId','$ruleGroupRelation->type','$ruleGroupRelation->createdBy','$ruleGroupRelation->updatedBy')";
        
        try {
            $id = $this->executeQuery($query, true)->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $id;
    }
    /**
     * Update RuleGroupRelation
     * @param RuleGroupRelation $ruleGroupRelation
     * @return NULL
     */
    private function updateRuleGroupRelation(RuleGroupRelation $ruleGroupRelation)
    {
        $query = "UPDATE ec_rule_group_relation 
        SET 
            ec_rule_id = '$ruleGroupRelation->ruleId',
            groups_id = '$ruleGroupRelation->groupId',
            type = $ruleGroupRelation->type,
            updated_by = '$ruleGroupRelation->updatedBy'
        WHERE 
            id = '$ruleGroupRelation->id'";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $ruleGroupRelation->id;
    }
    /**
     * Delete Rule Group Relation
     * @param String $id
     * @return NULL
     */
    public function deleteRuleGroupRelation($id)
    {
        $id = $this->realEscapeString($id);
        if(empty($id)) {
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_ASSIGN_RULE,"Rule assigned not found. Please try again!");
        }
        $query = "DELETE FROM 
            ec_rule_group_relation 
        WHERE 
            id = '$id'";
        try {
            CommonService::getInstance()->checkForeignKeyEntries("ec_rule_group_relation",$id);
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_DELETING_ASSIGN_RULE,"Error remove rule! Please try again");
        }
    }
        
    /**
     * Search Assigned Rule Details
     * @param SearchRuleRequest $request
     * @return Rule
     */
    public function getAssignedRule(SearchRuleRequest $request)
    {
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        $limitQuery = "";
        if(!empty($request->ruleId)) {
            $whereQuery .= " AND r.ec_rule_id='$request->ruleId'";
        }
        
        if(!empty($request->groupId)) {
            $whereQuery .= " AND r.groups_id='$request->groupId'";
        }
        if(!empty($request->type)) {
            $whereQuery .= " AND r.type='$request->type'";
        }
        if(!empty($request->name)) {
            $whereQuery .= " AND r.name LIKE '%$request->name%'";
        }
        if($request->startIndex !== "" && $request->endIndex !== "")
        {
            $limitQuery .= " LIMIT $request->startIndex,$request->endIndex";
        }
        $query = "SELECT
            ergr.id,
            r.name,
            r.rule,
            r.trashed,
            ergr.created_by,
            ergr.created_date,
            ergr.updated_by,
            ergr.updated_date,
            ergr.`type`,
            ergr.ec_rule_id,
            ergr.groups_id
        FROM
            ec_rule r
        INNER JOIN ec_rule_group_relation ergr ON
            ergr.ec_rule_id = r.id
        WHERE
            r.trashed IS NULL";
        try {
            $rules = $this->executeQueryForList($query.$whereQuery.$limitQuery,$this->mapper[RuleServiceMapper::SEARCH_ASSIGNED_RULES]);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_ASSIGNED_RULE,"Cannot fetch assigned rule details! Please try again");
        }
        return $rules;
    }
}