ApiProblem::getStatusCode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Guarded Authentication package.
4
 *
5
 * (c) Jafar Jabr <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Jafar\Bundle\GuardedAuthenticationBundle\Api\ApiResponse;
12
13
use Symfony\Component\HttpFoundation\Response;
14
15
/**
16
 * Class ApiProblem.
17
 *
18
 * @author Jafar Jabr <[email protected]>
19
 */
20
final class ApiProblem
21
{
22
    const VALIDATION_ERROR_TYPE            = 'Validation_Error';
23
24
    const INVALID_REQUEST_BODY_FORMAT_TYPE = 'Invalid_body_format';
25
26
    /**
27
     * @var array
28
     */
29
    private static $titles = [
30
        self::VALIDATION_ERROR_TYPE             => 'There was a validation error',
31
        self::INVALID_REQUEST_BODY_FORMAT_TYPE  => 'Invalid Json format sent',
32
    ];
33
34
    /**
35
     * @var int
36
     */
37
    private $statusCode;
38
39
    /**
40
     * @var string
41
     */
42
    private $type;
43
44
    /**
45
     * @var string
46
     */
47
    private $title;
48
49
    /**
50
     * @var string
51
     */
52
    private $detail;
53
54
    /**
55
     * ApiProblem constructor.
56
     *
57
     * @param int           $statusCode
58
     * @param null | string $type
59
     */
60
    public function __construct(int $statusCode, ?string $type = null)
61
    {
62
        $this->statusCode = $statusCode;
63
        if (null === $type) {
64
            $this->type  = 'about:blank';
65
            $this->title = isset(Response::$statusTexts[$statusCode]) ?
66
                Response::$statusTexts[$statusCode] : 'Unknown status code';
67
        } else {
68
            if (!isset(self::$titles[$type])) {
69
                throw new\InvalidArgumentException('not title for '.$type);
70
            }
71
        }
72
    }
73
74
    /**
75
     * @param $key
76
     * @param $value
77
     */
78
    public function set($key, $value)
79
    {
80
        $this->$key = $value;
81
    }
82
83
    /**
84
     * @return array
85
     */
86
    public function toArray()
87
    {
88
        return [
89
            'detail' => $this->detail,
90
            'status' => $this->statusCode,
91
            'type'   => $this->type,
92
            'title'  => $this->title,
93
        ];
94
    }
95
96
    /**
97
     * @return int
98
     */
99
    public function getStatusCode()
100
    {
101
        return $this->statusCode;
102
    }
103
}
104