<?php namespace FaZeBook\Page; require_once(__DIR__.'/../../Application/Page/PageInterface.php'); use Application\Page\PageInterface; use FaZeBook\Data; use FaZeBook\Session; class Search implements PageInterface { public function getId() { return "searchbar"; } public function hasNavigationItem() { return false; } public function getTitle() { return 'Suche'; } public function getViewScript() { return __DIR__.'/../../../view/app/search_results.php'; } public function getViewVariables() { $result['search_res'] = $this->searchResults(); $result['pageTarget'] = "viewprofile"; if (isset($_POST['pageTarget'])) { $result['pageTarget'] = htmlspecialchars($_POST['pageTarget']); } return $result; } //--------------- CLASS HELPER FUNCTIONS ---------------// private function searchResults () { if(isset($_POST["input"]) && $_POST['input'] != '') { $searchTerm = $_POST["input"]; $users = Data::getInstance()->listUsers(); $users = $this->sortByLevenshtein($searchTerm, $users); return array_values($users); } else { echo "<p>Bitte einen Suchbegriff eingeben!</p>"; } return []; } /* Credits to Mr Wladimir lossifowitsch Lewenstein, born 1935. The russian Mathematician who knew his shit about making dank algorithms. He received the Richard-W.-Hamming-Medal for his groundbreaking work */ private function sortByLevenshtein ($input, $users) { if($users == []){ return []; } else { $lev_array = []; foreach ($users as $user) { $userSubStrings = explode(" ", $user->getFullName()); $inputSubStrings = explode(" ", $input); /* Initialization of sorting parameters */ $pos = false; $lev = 0; $lev_min = 255; //Case insensitive search foreach ($userSubStrings as $u) { $u_low = strtolower($u); $lev_tmp = 255; foreach ($inputSubStrings as $i) { $i_low = strtolower($i); if(($pos === false) && ($i !== "")) $pos = strpos($u_low, $i_low); $lev_tmp = min($lev_tmp, levenshtein($i_low,$u_low)); } $lev += $lev_tmp; $lev_min = min($lev_min, $lev); } /* Create associative array to store users in array that share a levenshtein distance. Later used to sort the array by key. */ if($pos !== false) { $lev_array[$lev][] = $user; } elseif($lev_min < 3) { $lev_array[$lev + 255][] = $user; } } } ksort($lev_array); $res = []; foreach($lev_array as $pos_array) { foreach($pos_array as $a) { $res[] = $a; } } return $res; } }