JsonConverter   A
last analyzed

Coupling/Cohesion

Components 1
Dependencies 2

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 51
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A options() 0 8 1
A convert() 0 14 3
1
<?php
2
/**
3
* This file is part of the League.csv library
4
*
5
* @license http://opensource.org/licenses/MIT
6
* @link https://github.com/thephpleague/csv/
7
* @version 9.0.0
8
* @package League.csv
9
*
10
* For the full copyright and license information, please view the LICENSE
11
* file that was distributed with this source code.
12
*/
13
declare(strict_types=1);
14
15
namespace League\Csv;
16
17
use League\Csv\Exception\RuntimeException;
18
use Traversable;
19
20
/**
21
 * A class to convert CSV records into a Json string
22
 *
23
 * @package League.csv
24
 * @since   9.0.0
25
 * @author  Ignace Nyamagana Butera <[email protected]>
26
 */
27
class JsonConverter
28
{
29
    use ValidatorTrait;
30
31
    /**
32
     * PHP's json_encode options flags
33
     *
34
     * @var int
35
     */
36
    protected $options = 0;
37
38
    /**
39
     * Set PHP's json_encode options flags
40
     *
41
     * @param int $options
42
     *
43
     * @return self
44
     */
45 2
    public function options(int $options): self
46
    {
47 2
        $options = $this->filterMinRange($options, 0, __METHOD__.'() expectes the options to be a positive integer or 0, %s given');
48 2
        $clone = clone $this;
49 2
        $clone->options = $options;
50
51 2
        return $clone;
52
    }
53
54
    /**
55
     * Convert an Record collection into a Json string
56
     *
57
     * @param array|Traversable $records the CSV records collection
58
     *
59
     * @throws RuntimeException if the conversion fails
60
     *
61
     * @return string
62
     */
63 4
    public function convert($records): string
64
    {
65 4
        $records = $this->filterIterable($records, __METHOD__);
66 4
        if (!is_array($records)) {
67 4
            $records = iterator_to_array($records);
68
        }
69
70 4
        $json = @json_encode($records, $this->options, 2);
71 4
        if (JSON_ERROR_NONE === json_last_error()) {
72 2
            return $json;
73
        }
74
75 2
        throw new RuntimeException(json_last_error_msg());
76
    }
77
}
78