Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
2
Indexable
Never
    public function getMoreLikeThis($search){

        $helper = new Helper();
        $indexTags = new ElasticIndex('index_tags');
        $query = $this->getQuery('more_like_this', 'query', $search);
    
        $tags =  $indexTags->search([
            'size'=>5,
            'query' => $query,
        ]);

        $tags = array_filter($tags, function($tag) use ($search, $helper) {

            $d = preg_replace('/\s+/', ' ', $helper->removeAccents($tag->descricao));
            $s = preg_replace('/\s+/', ' ', $helper->removeAccents($search));

            return $d != $s;
        });

        $xtags = $tags;
        $tags = array_filter($tags, function($tag) use ($search) {
            return strlen($tag->descricao) > strlen($search);
        });

        if(empty($tags)){
            $tags = $xtags;
        }

        $tags = array_filter($tags, function($tag) use ($search) {
            $lowercaseString = mb_strtolower($tag->descricao, 'UTF-8');
            $words = preg_split('/\PL+/u', $lowercaseString, -1, PREG_SPLIT_NO_EMPTY);
            return count($words) != 1;
        });

        foreach($tags as $k => $tag){

            foreach($tags as $j => $xtag){

                if($tag->id == $xtag->id){
                    continue;
                }

                if(!isset($tags[$k])){
                    continue;
                }

                similar_text($tag->descricao, $xtag->descricao, $similarity);

                if($similarity > 95){
                    unset($tags[$k]);
                    sort($tags);
                    continue;
                }

            }
        }

        usort($tags, function($a, $b){
            return $a->score < $b->score; 
        });

        return array_slice($tags, 0, 3);
    }