JSON::translateObjects()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 12
c 0
b 0
f 0
nc 6
nop 1
dl 0
loc 16
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
1
<?php
2
/**
3
 * This file is part of the Divergence package.
4
 *
5
 * (c) Henry Paradiz <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Divergence\Helpers;
12
13
/**
14
 * JSON
15
 *
16
 * @package Divergence
17
 * @author Henry Paradiz <[email protected]>
18
 * @author  Chris Alfano <[email protected]>
19
 */
20
class JSON
21
{
22
    public static $inputStream = 'php://input'; // this is a setting so that unit tests can provide a fake stream :)
23 14
    public static function getRequestData($subkey = false)
24
    {
25 14
        if (!$requestText = file_get_contents(static::$inputStream)) {
26 8
            return false;
27
        }
28
29 7
        $data = json_decode($requestText, true);
30
31 7
        return $subkey ? $data[$subkey] : $data;
32
    }
33
34 3
    public static function respond($data)
35
    {
36 3
        header('Content-type: application/json', true);
37 3
        echo json_encode($data);
38
    }
39
40 1
    public static function translateAndRespond($data)
41
    {
42 1
        static::respond(static::translateObjects($data));
43
    }
44
45 1
    public static function error($message)
46
    {
47 1
        static::respond([
48 1
            'success' => false,
49 1
            'message' => $message,
50 1
        ]);
51
    }
52
53 54
    public static function translateObjects($input)
54
    {
55 54
        if (is_object($input)) {
56 29
            if (method_exists($input, 'getData')) {
57 29
                return $input->getData();
58 3
            } elseif ($data = $input->data) {
59 3
                return static::translateObjects($data);
60
            }
61 3
            return $input;
62 54
        } elseif (is_array($input)) {
63 54
            foreach ($input as &$item) {
64 54
                $item = static::translateObjects($item);
65
            }
66 54
            return $input;
67
        } else {
68 54
            return $input;
69
        }
70
    }
71
}
72