Completed
Pull Request — master (#363)
by Anton
06:05
created

CliResponse::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 5
ccs 0
cts 5
cp 0
crap 2
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
        $body = new Stream('php://temp', 'wb+');
36
        $body->write($this->encode($data));
37
        parent::__construct($body, $status);
38
    }
39
40
    /**
41
     * Encode the provided data to JSON.
42
     *
43
     * @param mixed $data
44
     * @return string
45
     * @throws InvalidArgumentException if unable to encode the $data to JSON.
46
     */
47
    private function encode($data)
48
    {
49
        if (is_resource($data)) {
50
            throw new InvalidArgumentException('Cannot encode resources');
51
        }
52
53
        // just print to console as key-value pair
54
        $output = array();
55
        array_walk_recursive($data, function ($value, $key) use (&$output) {
56
            $output[] = $key .': '. $value;
57
        });
58
59
        return join("\n", $output) . "\n";
60
    }
61
}
62