Passed
Push — master ( a5c74c...eed2cc )
by Radosław
02:38
created

Auction::toApiRepresentation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
crap 6
1
<?php
2
3
namespace Radowoj\Yaah;
4
5
use Radowoj\Yaah\Constants\AuctionFids;
6
7
class Auction
8
{
9
    const MAX_PHOTOS = 8;
10
11
    protected $fields = [];
12
13
    protected $photos = [];
14
15
    public function __construct(array $fields = [])
16
    {
17
        $this->fields = $fields;
18
    }
19
20
21
    public function setPhotos(array $photos)
22
    {
23
        $photosCount = count($photos);
24
25
        if ($photosCount > self::MAX_PHOTOS) {
26
            throw new Exception("Photo files limit exceeded, " . self::MAX_PHOTOS . " allowed, " . $photosCount . " given");
27
        }
28
29
        $this->photos = $photos;
30
    }
31
32
33
    public function toApiRepresentation()
34
    {
35
        $fields = [];
36
37
        foreach($this->fields as $fid => $value) {
38
            $fields[] = (new Field($fid, $value))->toArray();
39
        }
40
41
        $this->addPhotoFields($fields);
42
43
        return [
44
            'fields' => $fields,
45
        ];
46
    }
47
48
49
    public function fromApiRepresentation(array $fields)
50
    {
51
        $this->fields = [];
52
        $this->photos = [];
53
54
        foreach($fields as $apiField) {
55
            $field = new Field(0, '');
56
            $field->fromArray((array)$apiField);
57
            $this->fields[$field->getFid()] = $field->getValue();
58
        }
59
    }
60
61
62
    protected function addPhotoFields(array& $fields)
63
    {
64
        $count = count($this->photos);
65
        if (!$count) {
66
            return;
67
        }
68
69
        $index = 0;
70
        foreach ($this->photos as $photo) {
71
            if (!is_readable($photo)) {
72
                throw new Exception("Photo file {$photo} is not readable");
73
            }
74
75
            $fields[] = (new Field(AuctionFids::FID_PHOTO + $index, file_get_contents($photo), Field::VALUE_IMAGE))->toArray();
76
            $index++;
77
        }
78
    }
79
80
}
81