JsonApiConverter   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 32
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A contentType() 0 3 1
A convert() 0 16 2
1
<?php
2
3
/**
4
 * This file is part of Cors
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\Cors\Infrastructure\Converter;
13
14
use Slick\Cors\Infrastructure\Converter;
15
use Slick\ErrorHandler\Exception\ExceptionInspector;
16
use Slick\JSONAPI\JsonApi;
17
use Slick\JSONAPI\Object\ErrorObject;
18
use Throwable;
19
20
/**
21
 * JsonApiConverter
22
 *
23
 * @package Slick\Cors\Infrastructure\Converter
24
 */
25
final class JsonApiConverter implements Converter
26
{
27
28
    use JsonMethods;
29
30
    /**
31
     * @inheritDoc
32
     */
33
    public function convert(Throwable $throwable): string
34
    {
35
        $inspector = new ExceptionInspector($throwable);
36
        $jsonApiError = new ErrorObject(
37
            title: $this->clearTitle($throwable),
38
            detail: $this->details($throwable, $inspector),
39
            status: (string) $inspector->statusCode()
40
        );
41
        $response = [
42
            "jsonapi" => ["version" => JsonApi::JSON_API_11],
43
            "errors" => [
44
                $jsonApiError->withIdentifier(uniqid())
45
            ]
46
        ];
47
        $jsonResponse = json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
48
        return $jsonResponse ?: '';
49
    }
50
51
    /**
52
     * @inheritDoc
53
     */
54
    public function contentType(): string
55
    {
56
        return 'application/vnd.api+json';
57
    }
58
}
59