1 | <?php |
||
2 | |||
3 | namespace ByJG\RestServer; |
||
4 | |||
5 | use ByJG\Serializer\SerializerObject; |
||
6 | |||
7 | class ResponseBag |
||
8 | { |
||
9 | |||
10 | const AUTOMATIC = 0; |
||
11 | const SINGLE_OBJECT = 1; |
||
12 | const OBJECT_LIST = 2; |
||
13 | |||
14 | protected $collection = []; |
||
15 | protected $serializationRule = ResponseBag::AUTOMATIC; |
||
16 | |||
17 | /** |
||
18 | * @param string|mixed $object |
||
19 | */ |
||
20 | 13 | public function add($object) |
|
21 | { |
||
22 | 13 | if (!is_object($object) && !is_array($object)) { |
|
23 | 3 | $object = [ $object ]; |
|
24 | } |
||
25 | |||
26 | 13 | if ($this->serializationRule !== ResponseBag::SINGLE_OBJECT) { |
|
27 | 10 | $this->collection[] = $object; |
|
28 | 10 | return; |
|
29 | } |
||
30 | |||
31 | 3 | if (is_object($object)) { |
|
32 | 1 | $object = [$object]; |
|
33 | } |
||
34 | 3 | $this->collection = array_merge($this->collection, $object); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
35 | 3 | } |
|
36 | |||
37 | /** |
||
38 | * @param bool $buildNull |
||
39 | * @param bool $onlyString |
||
40 | * @return array |
||
41 | */ |
||
42 | 15 | public function process($buildNull = true, $onlyString = false) |
|
43 | { |
||
44 | 15 | $collection = (array)$this->collection; |
|
45 | 15 | if (count($collection) === 1 |
|
46 | 15 | && $this->serializationRule !== ResponseBag::OBJECT_LIST && isset($collection[0]) |
|
47 | ) { |
||
48 | 9 | $collection = $collection[0]; |
|
49 | } |
||
50 | |||
51 | 15 | $object = new SerializerObject($collection); |
|
52 | return $object |
||
53 | 15 | ->setOnlyString($onlyString) |
|
54 | 15 | ->setBuildNull($buildNull) |
|
55 | 15 | ->build(); |
|
56 | } |
||
57 | |||
58 | public function getCollection() |
||
59 | { |
||
60 | return $this->collection; |
||
61 | } |
||
62 | |||
63 | 6 | public function serializationRule($value) |
|
64 | { |
||
65 | 6 | $this->serializationRule = $value; |
|
66 | 6 | } |
|
67 | } |
||
68 |