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

CliResponse   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 38
ccs 0
cts 17
cp 0
rs 10
wmc 3
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A encode() 0 14 2
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