Passed
Pull Request — master (#87)
by Dmitriy
02:45
created

ApiResponseDataFactory::createFromResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 2
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 13
    public function createFromResponse(DataResponse $response): ApiResponse
13
    {
14 13
        if ($response->getStatusCode() !== Status::OK) {
15 6
            return $this->createErrorResponse()
16 6
                ->setErrorCode($response->getStatusCode())
17 6
                ->setErrorMessage($this->getErrorMessage($response));
18
        }
19
20 7
        return $this->createSuccessResponse()
21 7
            ->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

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