Completed
Push — master ( cb5363...63e3c2 )
by Nikola
02:41
created

IpAddressIdentityGenerator::getIdentity()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.4042

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
ccs 5
cts 9
cp 0.5556
rs 9.2
cc 4
eloc 9
nc 4
nop 1
crap 5.4042
1
<?php
2
/**
3
 * This file is part of the Rate Limit package.
4
 *
5
 * Copyright (c) Nikola Posa
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
declare(strict_types=1);
12
13
namespace RateLimit\Identity;
14
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
18
/**
19
 * @author Nikola Posa <[email protected]>
20
 */
21
final class IpAddressIdentityGenerator implements IdentityGeneratorInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26 2
    public function getIdentity(RequestInterface $request) : string
27
    {
28 2
        if (!$request instanceof ServerRequestInterface) {
29
            return 'ANONYMOUS';
30
        }
31
32 2
        $serverParams = $request->getServerParams();
33
34 2
        if (array_key_exists('HTTP_CLIENT_IP', $serverParams)) {
35 2
            return $serverParams['HTTP_CLIENT_IP'];
36
        }
37
38
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $serverParams)) {
39
            return $serverParams['HTTP_X_FORWARDED_FOR'];
40
        }
41
42
        return $serverParams['REMOTE_ADDR'] ?? 'UNKNOWN';
43
    }
44
}
45