EntityApiSerializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * ownCloud - News
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Bernhard Posselt <[email protected]>
9
 * @copyright Bernhard Posselt 2014
10
 */
11
12
namespace OCA\News\Controller;
13
14
use \OCA\News\Db\IAPI;
15
16
17
class EntityApiSerializer {
18
19
    private $level;
20
21
    public function __construct($level) {
22
        $this->level = $level;
23
    }
24
25
26
    /**
27
     * Call toAPI() method on all entities. Works on
28
     *
29
     * @param mixed $data :
30
     * * Entity
31
     * * Entity[]
32
     * * array('level' => Entity[])
33
     * * Response
34
     * @return array|mixed
35
     */
36
    public function serialize($data) {
37
38
        if($data instanceof IAPI) {
39
            return [$this->level => [$data->toAPI()]];
40
        }
41
42
        if(is_array($data) && array_key_exists($this->level, $data)) {
43
            $data[$this->level] = $this->convert($data[$this->level]);
44
        } elseif(is_array($data)) {
45
            $data = [$this->level => $this->convert($data)];
46
        }
47
48
        return $data;
49
    }
50
51
52
    private function convert($entities) {
53
        $converted = [];
54
55
        foreach($entities as $entity) {
56
            if($entity instanceof IAPI) {
57
                $converted[] = $entity->toAPI();
58
59
            // break if it contains anything else than entities
60
            } else {
61
                return $entities;
62
            }
63
        }
64
65
        return $converted;
66
    }
67
68
}