Laravel 8: Validate that URL is a local URL

raw

app/Rules/LocalUrl.php

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
 
namespace App\Rules;
 
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Validation\Validator;
 
/**
 * Check if the given URL has the current local domain name
 */
class LocalUrl implements Rule
{
    public function validate(string $attribute, $value, $params, Validator $validator)
    {
        return $this->passes($attribute, $value);
    }
 
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $currentUrl = \URL::current();
        $currentParts = $this->getRelevantParts(parse_url($currentUrl));
        $targetParts  = $this->getRelevantParts(parse_url($value));
        return $currentParts == $targetParts;
    }
 
    protected function getRelevantParts(array $urlParts)
    {
        return [
            'scheme' => $urlParts['scheme'] ?? null,
            'host'   => $urlParts['host'] ?? null,
            'port'   => $urlParts['port'] ?? null,
        ];
    }
 
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Redirects to external URLs are not supported.';
    }
}
 
Christian Weiske Christian Weiske
owner

History