Completed
Push — master ( ffb215...f806ab )
by Anton
11s
created

CliResponse::encode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 14
ccs 0
cts 11
cp 0
crap 6
rs 9.4285
c 1
b 0
f 1
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Bluz\Cli;
13
14
use InvalidArgumentException;
15
use Zend\Diactoros\Response;
16
use Zend\Diactoros\Stream;
17
18
/**
19
 * CLI response.
20
 *
21
 * Allows creating a response by passing data to the constructor; by default,
22
 * serializes the data to JSON, sets a status code of 200 and sets the
23
 * Content-Type header to application/json.
24
 */
25
class CliResponse extends Response
26
{
27
    /**
28
     * Create a console response with the given data.
29
     *
30
     * @param mixed $data Data to convert to string
31
     * @param int $status Integer status code for the response; 200 by default.
32
     * @throws InvalidArgumentException if unable to encode the $data to JSON.
33
     */
34
    public function __construct($data, $status = 200)
35
    {
36
        $body = new Stream('php://temp', 'wb+');
37
        $body->write($this->encode($data));
38
        parent::__construct($body, $status);
39
    }
40
41
    /**
42
     * Encode the provided data to JSON.
43
     *
44
     * @param mixed $data
45
     * @return string
46
     * @throws InvalidArgumentException if unable to encode the $data to JSON.
47
     */
48
    private function encode($data)
49
    {
50
        if (is_resource($data)) {
51
            throw new InvalidArgumentException('Cannot encode resources');
52
        }
53
54
        // just print to console as key-value pair
55
        $output = array();
56
        array_walk_recursive($data, function ($value, $key) use (&$output) {
57
            $output[] = $key .': '. $value;
58
        });
59
60
        return join("\n", $output) . "\n";
61
    }
62
}
63