EntitiesBuilder::collection()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Osnova\Support;
4
5
use Osnova\Api\ApiProvider;
6
use Osnova\OsnovaResource;
7
use Psr\Http\Message\ResponseInterface;
8
9
class EntitiesBuilder
10
{
11
    protected $class;
12
    protected $data = [];
13
    protected $apiProvider;
14
    protected $resource;
15
16
    public function __construct(string $class)
17
    {
18
        $this->class = $class;
19
    }
20
21
    public static function make(string $class)
22
    {
23
        return new static($class);
24
    }
25
26
    public function from(array $data)
27
    {
28
        $this->data = $data;
29
30
        return $this;
31
    }
32
33
    public function fromResponse(ResponseInterface $response)
34
    {
35
        $this->data = json_decode((string) $response->getBody(), true)['result'] ?? [];
36
37
        return $this;
38
    }
39
40
    public function with(ApiProvider $apiProvider = null, OsnovaResource $resource = null)
41
    {
42
        return $this->withApiProvider($apiProvider)
43
            ->withOsnovaResource($resource);
44
    }
45
46
    public function withApiProvider(ApiProvider $apiProvider = null)
47
    {
48
        $this->apiProvider = $apiProvider;
49
50
        return $this;
51
    }
52
53
    public function withOsnovaResource(OsnovaResource $resource = null)
54
    {
55
        $this->resource = $resource;
56
57
        return $this;
58
    }
59
60
    public function item()
61
    {
62
        return new $this->class($this->data, $this->apiProvider, $this->resource);
63
    }
64
65
    public function collection()
66
    {
67
        return array_map(function (array $data) {
68
            return new $this->class($data, $this->apiProvider, $this->resource);
69
        }, $this->data);
70
    }
71
}
72