Completed
Pull Request — master (#3)
by Joao
02:07
created

ResponseBag::serializationRule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace ByJG\RestServer;
4
5
use ByJG\RestServer\Exception\HttpResponseException;
6
use ByJG\Serializer\SerializerObject;
7
8
class ResponseBag
9
{
10
11
    const AUTOMATIC = 0;
12
    const SINGLE_OBJECT = 1;
13
    const ARRAY = 2;
14
15
    protected $collection = [];
16
    protected $serializationRule = ResponseBag::AUTOMATIC;
17
18
    public function add($object)
19
    {
20
        if (is_string($object)) {
21
            $object = [ $object ];
22
        }
23
        if (!is_object($object) && !is_array($object)) {
24
            throw new HttpResponseException('You can add only object');
25
        }
26
27
        if ($this->serializationRule !== ResponseBag::SINGLE_OBJECT) {
28
            $this->collection[] = $object;
29
            return;
30
        }
31
32
        if (is_object($object)) {
33
            $object = [$object];
34
        }
35
        $this->collection = array_merge($this->collection, $object);
36
    }
37
38
    /**
39
     * @return array
40
     */
41
    public function process()
42
    {
43
        $collection = (array)$this->collection;
44
        if (count($collection) === 1 && $this->serializationRule !== ResponseBag::ARRAY && isset($collection[0])) {
45
            $collection = $collection[0];
46
        }
47
        
48
        $object = new SerializerObject($collection);
49
        return $object->build();
50
    }
51
52
    public function getCollection()
53
    {
54
        return $this->collection;
55
    }
56
57
    public function serializationRule($value)
58
    {
59
        $this->serializationRule = $value;
60
    }
61
}
62