summaryrefslogtreecommitdiff
path: root/src/Http/RequestServiceProvider.php
blob: 37f8c60464d6a48a2cc3fb4156414ed87cec5562 (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
38
39
40
41
42
43
44
45
<?php

namespace Engelsystem\Http;

use Engelsystem\Container\ServiceProvider;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class RequestServiceProvider extends ServiceProvider
{
    public function register()
    {
        $config = $this->app->get('config');
        $trustedProxies = $config->get('trusted_proxies', []);

        if (!is_array($trustedProxies)) {
            $trustedProxies = empty($trustedProxies) ? [] : explode(',', preg_replace('~\s+~', '', $trustedProxies));
        }

        /** @var Request $request */
        $request = $this->app->call([Request::class, 'createFromGlobals']);
        $this->setTrustedProxies($request, $trustedProxies);

        $this->app->instance(Request::class, $request);
        $this->app->instance(SymfonyRequest::class, $request);
        $this->app->instance('request', $request);
    }

    /**
     * Set the trusted Proxies
     *
     * Required for unit tests (static methods can't be mocked)
     *
     * @param Request $request
     * @param array   $proxies
     * @param int     $trustedHeadersSet
     * @codeCoverageIgnore
     */
    protected function setTrustedProxies(
        $request,
        $proxies,
        $trustedHeadersSet = Request::HEADER_FORWARDED | Request::HEADER_X_FORWARDED_ALL
    ) {
        $request->setTrustedProxies($proxies, $trustedHeadersSet);
    }
}