Completed
Push — master ( 6e52f0...d9a404 )
by Alexandre
02:29
created

ErrorResponse   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 0
cts 26
cp 0
rs 10
c 0
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 0 28 7
A containsNotAsciiChar() 0 3 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Alexandre
5
 * Date: 31/12/2017
6
 * Time: 17:05
7
 */
8
9
namespace OAuth2OLD\Endpoint\Server\Messages\AccessToken;
10
11
12
use GuzzleHttp\Psr7\Response;
13
use GuzzleHttp\Psr7\Uri;
14
use Psr\Http\Message\UriInterface;
15
16
class ErrorResponse extends Response
17
{
18
    const errors = [
19
        'invalid_request',
20
        'invalid_client',
21
        'invalid_grant',
22
        'unauthorized_client',
23
        'unsupported_grant_type',
24
        'invalid_scope'
25
    ];
26
27
    /**
28
     * ErrorResponse constructor.
29
     * @param string $error
30
     * @param null|string $errorDescription
31
     * @param null|string $errorUri
32
     * @param int $status
33
     * @param array $headers
34
     * @throws \Exception
35
     */
36
    public function __construct(string $error, ?string $errorDescription = null, ?string $errorUri = null, int $status = 400, array $headers = [])
37
    {
38
        if ($this->containsNotAsciiChar($error)) {
39
            throw new \Exception('Malformed error type. Expect ascii string. Got : ' . $error);
40
        }
41
42
        if (!in_array($error, self::errors)) {
43
            throw new \Exception('Unexpected error type. Expect one of : ' . implode(', ', self::errors));
44
        }
45
46
        $data = ['error' => $error];
47
48
        if ($errorDescription) {
49
            if ($this->containsNotAsciiChar($errorDescription)) {
50
                throw new \Exception('Malformed error description. Expect ascii string. Got : ' . $errorDescription);
51
            }
52
            $data['error_description'] = $errorDescription;
53
        }
54
55
        if ($errorUri) {
56
            if ($this->containsNotAsciiChar($errorUri)) {
57
                throw new \Exception('Malformed error uri. Expect ascii string. Got : ' . $errorUri);
58
            }
59
60
            $data['error_uri'] = $errorDescription;
61
        }
62
63
        parent::__construct($status, $headers, json_encode($data));
64
    }
65
66
    private function containsNotAsciiChar(string $string)
67
    {
68
        return preg_match('/[^\x20-\x7e]/', $string);
69
    }
70
}