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

ApiResponseDataFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 37
ccs 17
cts 18
cp 0.9444
rs 10
c 0
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A createSuccessResponse() 0 3 1
A createResponse() 0 3 1
A getErrorMessage() 0 8 3
A createErrorResponse() 0 3 1
A createFromResponse() 0 10 2
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