Test Failed
Pull Request — master (#87)
by Dmitriy
02:46
created

ApiResponseDataFactory::createFromResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Infrastructure\Http\Response;
6
7
use Yiisoft\DataResponse\DataResponse;
8
use Yiisoft\Http\Status;
9
10
final class ApiResponseDataFactory
11
{
12
    public function createFromResponse(DataResponse $response): ApiResponse
13
    {
14
        if ($response->getStatusCode() !== Status::OK) {
15
            return $this
16
                ->createErrorResponse()
17
                ->setErrorCode($response->getStatusCode())
18
                ->setErrorMessage($this->getErrorMessage($response));
19
        }
20
21
        return $this
22
            ->createSuccessResponse()
23
            ->setData($response->getData());
0 ignored issues
show
Bug introduced by
It seems like $response->getData() can also be of type object; however, parameter $data of App\Infrastructure\Http\...\ApiResponse::setData() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

23
            ->setData(/** @scrutinizer ignore-type */ $response->getData());
Loading history...
24
    }
25
26
    public function createSuccessResponse(): ApiResponse
27
    {
28
        return $this
29
            ->createResponse()
30
            ->setStatus('success');
31
    }
32
33
    public function createErrorResponse(): ApiResponse
34
    {
35
        return $this
36
            ->createResponse()
37
            ->setStatus('failed');
38
    }
39
40
    public function createResponse(): ApiResponse
41
    {
42
        return new ApiResponse();
43
    }
44
45
    private function getErrorMessage(DataResponse $response): string
46
    {
47
        $data = $response->getData();
48
        if (is_string($data) && !empty($data)) {
49
            return $data;
50
        }
51
52
        return 'Unknown error';
53
    }
54
}
55