Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
RequestRebuilder
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
2 / 2
7
100.00% covered (success)
100.00%
1 / 1
 rebuild
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 wasRequestForwardedByHttps
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; under version 2
7 * of the License (non-upgradable).
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 *
18 * Copyright (c) 2020 (original work) Open Assessment Technologies SA
19 */
20
21declare(strict_types=1);
22
23namespace oat\tao\model\http;
24
25use Psr\Http\Message\RequestInterface;
26
27class RequestRebuilder
28{
29    /**
30     * Takes care about schema rebuilding for the offloaded request
31     * Port rebuilding may be added later ( HTTP_X_FORWARDED_PORT )
32     */
33    public function rebuild(RequestInterface $request): RequestInterface
34    {
35        $url = $request->getUri();
36
37        if ('http' === $url->getScheme() && $this->wasRequestForwardedByHttps($request)) {
38            $url = $url->withScheme('https');
39        }
40
41        return $request->withUri($url);
42    }
43
44    private function wasRequestForwardedByHttps(RequestInterface $request): bool
45    {
46        $https = $request->hasHeader('x-forwarded-proto')
47            && $request->getHeader('x-forwarded-proto')[0] === 'https';
48        $https = $https || ($request->hasHeader('x-forwarded-ssl')
49                && $request->getHeader('x-forwarded-ssl')[0] === 'on');
50
51        return $https;
52    }
53}