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

CliResponse::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 1
eloc 4
c 2
b 1
f 1
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 2
rs 9.4285
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