aboutsummaryrefslogtreecommitdiff
path: root/app/Http/Middleware/GuestbookValidate.php
blob: b2218bb01d96847f4ac9a0ecffc66c935e46238c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class GuestbookValidate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (
            !$request->validate([
                'name' => 'required',
                'message' => 'required'
            ]) ||
            $this->containsUrl($request->get('message')) ||
            $this->containsUrl($request->get('name'))
        ) {
            return response()->view('errors.guestbook-invalid', [], 400);
        }
        return $next($request);
    }

    public function containsUrl($str) {
        $matches = [];
        $pattern = '/\b(?:https?|ftp|www)(:\/\/)*[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
        preg_match_all($pattern, $str, $matches);
        return count($matches[0]);
    }
}