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

CliResponse   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 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
        $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