ZitatController.php 1.81 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ZitatController extends Controller
{
    public function zitatSuche(Request $request)
    {
        $validResults = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
12
        if ($request->filled("q")) {
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
            # The user searched for something
            $fileName    = storage_path() . "/app/public/zitate.txt";
            $fileContent = file_get_contents($fileName);

            # Die Suchworte sind UND verknüpft, müssen aber nicht als gesamtes Wort vorkommen
            $all = explode(PHP_EOL, $fileContent);

            $words = preg_split("/\s+/", $request->input('q'));

            # Loop through all
            foreach ($all as $zitat) {
                $valid = true;
                # A Result isn't valid when it doesn't Contain every search word
                foreach ($words as $word) {
                    if (stripos($zitat, $word) === false) {
                        $valid = false;
                        break;
                    }
                }
                if ($valid) {
                    # This Result is valid. We'll add it Sorted by author
                    if (preg_match("/^\"([^\"]+)\"\s(.*)$/", $zitat, $matches)) {
35 36
                        $quote  = trim($matches[1]);
                        $author = trim($matches[2]);
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

                        if (isset($validResults[$author])) {
                            $validResults[$author][] = $quote;
                        } else {
                            $validResults[$author] = [$quote];
                        }
                    }
                }
            }
        }

        return view('zitatsuche')
            ->with('title', 'Zitatsuche MetaGer')
            ->with('navbarFocus', 'dienste')
            ->with('results', $validResults)
            ->with('q', $request->input('q', ''));
    }
}