Completed
Push — master ( 689084...daf696 )
by Joao
10s
created

src/ResponseBag.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
     * @param bool $buildNull
40
     * @param bool $onlyString
41
     * @return array
42
     */
43
    public function process($buildNull = true, $onlyString = false)
44
    {
45
        $collection = (array)$this->collection;
46
        if (count($collection) === 1 && $this->serializationRule !== ResponseBag::ARRAY && isset($collection[0])) {
47
            $collection = $collection[0];
48
        }
49
        
50
        $object = new SerializerObject($collection);
51
        return $object
0 ignored issues
show
The method setBuildNull cannot be called on $object->setOnlyString($onlyString) (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
52
            ->setOnlyString($onlyString)
53
            ->setBuildNull($buildNull)
54
            ->build();
55
    }
56
57
    public function getCollection()
58
    {
59
        return $this->collection;
60
    }
61
62
    public function serializationRule($value)
63
    {
64
        $this->serializationRule = $value;
65
    }
66
}
67