<?php

declare (strict_types = 1);
namespace library\utils;
// +----------------------------------------------------------------------
// | 敏感词过滤类
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-10-04 18:31
// +----------------------------------------------------------------------


use DfaFilter\SensitiveHelper;

class Lustre{
    private $client=null;
    private $content="";
    private $mark = "*";
    private $marks = "***";
    
    /**
     * 构造函数
     * @param type $content
     */
    public function __construct($content){
        $this->content = empty($content)?"":$content;
        $wordFilePath = app()->getRootPath(). 'library/utils/lustre/words.txt';
        $this->client = SensitiveHelper::init()->setTreeByFile($wordFilePath);
    }
    /**
     * 追加敏感词
     * @param type $words
     * @return boolean
     */
    static public function putEndWords($words=""){
        if($words==""){
            return false;
        }
        $file = app()->getRootPath().'library/utils/lustre/words.txt';
        $byte = file_put_contents($file,PHP_EOL.$words,FILE_APPEND | LOCK_EX);
        if(intval($byte)>0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取敏感词数组列表
     * @return type
     */
    static public function getWordsAr(){
        $file = app()->getRootPath().'library/utils/lustre/words.txt';
        $content = file_get_contents($file);
        $contentAr = explode(PHP_EOL,$content);
        return $contentAr;
    }
    /**
     * 检测是否含有敏感词
     */
    public function checkWords(){
        return $this->client->islegal($this->content);
    }
    /**
     * 敏感词替换为*为例（会替换为相同字符长度的*）
     * @param type $type
     * @return type
     */
    public function markReplace($type=1){
        $filterContent = "";
        if($type==1){
            $filterContent = $this->client->replace($this->content,$this->mark, true);
        }else{
            $filterContent = $this->client->replace($this->content,$this->marks);
        }
        return $filterContent;
    }
    /**
     * 
     * @param type $type
     * @return type
     */
    public function getBadWord($count=0){
        $sensitiveWordGroup = [];
        if($count==0){
            $sensitiveWordGroup = $this->client->getBadWord($this->content);
        }else{
            $sensitiveWordGroup = $this->client->getBadWord($this->content,1,$count);
        }
        return $sensitiveWordGroup;
    }
}

