Example #1
0
	/**
	 * Hook handler to save the index data for a given model record.
	 *
	 * @param \Model $model
	 *
	 * @return bool
	 */
	public static function ModelPreSaveHandler(\Model $model){
		// Only process models that have a search index on them.
		if(!$model::$HasSearch) return true;

		$str = $model->getSearchIndexString();

		// Lowercase it.
		$str = strtolower($str);

		// Convert this string to latin.
		$str = \Core\str_to_latin($str);

		// Contractions get dropped with no space.
		$str = str_replace("'", '', $str);

		// Skip punctuation.
		$str = preg_replace('/[^a-z0-9 ]/', ' ', $str);

		$parts = explode(' ', $str);

		// Conjunction words to skip
		$skips = self::GetSkipWords();
		
		// Generate the plain text index and only run the doublemetaphone conversion if it changes.
		// This is because that function is painfully slow, so the less it runs the better!
		foreach($parts as $k => $word){
			if(!$word){
				// Skip blank words
				unset($parts[$k]);
			}
			elseif(in_array($word, $skips)){
				// Skip "skip" words
				unset($parts[$k]);	
			}
			// OK to add, no else needed here.
		}
		
		// Strip uniques
		$parts = array_unique($parts);
		
		$model->set('search_index_str', implode(' ', $parts));
		
		if($model->changed('search_index_str')){
			// It changed, NOW generate the doublemetaphone conversion strings.
			$primary = [];
			$secondary = [];
			foreach($parts as $k => $word){
				$it = new DoubleMetaPhone($word);
				$primary[] = $it->primary;
				$secondary[] = $it->secondary;
			}
			
			$model->set('search_index_pri', implode(' ', $primary));
			$model->set('search_index_sec', implode(' ', $secondary));
		}

		return true;
	}