<?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.';
    }
}
