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

ApiResponseDataFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 37
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
    public function createFromResponse(DataResponse $response): ApiResponse
13
    {
14
        if ($response->getStatusCode() !== Status::OK) {
15
            return $this->createErrorResponse()
16
                ->setErrorCode($response->getStatusCode())
17
                ->setErrorMessage($this->getErrorMessage($response));
18
        }
19
20
        return $this->createSuccessResponse()
21
            ->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
    public function createSuccessResponse(): ApiResponse
25
    {
26
        return $this->createResponse()->setStatus('success');
27
    }
28
29
    public function createErrorResponse(): ApiResponse
30
    {
31
        return $this->createResponse()->setStatus('failed');
32
    }
33
34
    public function createResponse(): ApiResponse
35
    {
36
        return new ApiResponse();
37
    }
38
39
    private function getErrorMessage(DataResponse $response): string
40
    {
41
        $data = $response->getData();
42
        if (is_string($data) && !empty($data)) {
43
            return $data;
44
        }
45
46
        return 'Unknown error';
47
    }
48
}
49