<?php

namespace App\Http\Middleware;

use Illuminate\Contracts\Config\Repository;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * Set with TRUSTED_PROXIES: a comma separated list of IPs/CIDRs, or '*' to
     * trust whoever is calling. The default keeps the historical value so the
     * existing server behaves exactly as before; the containerised deployment
     * sets '*' in the stack, because behind Traefik the proxy reaches the
     * container from a docker network IP that changes on every redeploy — and
     * without trusting it Laravel builds http:// URLs for an https site and the
     * admin panel breaks on mixed content. '*' is only safe when the app is not
     * reachable except through the proxy, which is the case in the stack (no
     * published ports).
     *
     * @var array|string
     */
    protected $proxies;

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;

    public function __construct(Repository $config)
    {
        parent::__construct($config);

        $proxies = env('TRUSTED_PROXIES', '192.168.0.11');

        $this->proxies = ($proxies === '*' || $proxies === '**')
            ? $proxies
            : array_values(array_filter(array_map('trim', explode(',', (string) $proxies))));
    }
}
