<?php

if (!function_exists('load_polymorphic_dependencies')) {
    function load_polymorphic_dependencies(
        Illuminate\Database\Eloquent\Collection $collection,
        $polymorphic_name,
        $model_type,
        array $relation,
        $poly_type = null,
        $poly_id = null
    ) {
        if (empty($poly_type)) {
            $poly_type = $polymorphic_name."_type";
        }

        if (empty($poly_id)) {
            $poly_id = $polymorphic_name."_id";
        }
        $new_collection = new \Illuminate\Database\Eloquent\Collection();

        foreach ($collection as $model) {
            if ($model->$polymorphic_name instanceof $model_type) {
                $new_collection->add($model->$polymorphic_name);
            }
        }

        $new_collection->load($relation);
        return $collection;
    }
}

if (!function_exists('fulltext_search_term')) {
    function fulltext_search_term($term, $allInclusive = true)
    {
        if (empty($term)) {
            return $term;
        }
        $term = str_replace("@", " ", $term);
        $term = str_replace("+", " ", $term);
        $term = str_replace("-", " ", $term);
        $term = str_replace("<", " ", $term);
        $term = str_replace(">", " ", $term);
        $term = str_replace("(", " ", $term);
        $term = str_replace(")", " ", $term);
        $term = str_replace("~", " ", $term);
        $term = str_replace("*", " ", $term);

        // $words = explode(" ", trim($term));
        $words = preg_split('/("[^"]*")|\h+/', $term, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
        $terms = array();

        foreach ($words as $word) {
            if (!empty($word)) {
                if ($allInclusive) {
                    $word = "+".$word;
                }
                if (!($word[0] == '"' && $word[strlen($word) - 1] == '"')) {
                    $word = $word."*";
                }
                $terms[] = $word;
            }
        }

        return implode(" ", $terms);
    }
}
