Completed
Push — master ( 16aae2...147747 )
by ignace nyamagana
05:03 queued 03:16
created

JsonConverter::convert()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 2
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
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
     * Convert an Record collection into a Json string
33
     *
34
     * @param array|Traversable $records the CSV records collection
35
     *
36
     * @return string
37
     */
38 4
    public function convert($records, int $options = 0): string
39
    {
40 4
        $options = $this->filterMinRange($options, 0, 'The options must be a positive integer or 0');
41 4
        $records = $this->filterIterable($records);
42 4
        if (!is_array($records)) {
43 4
            $records = iterator_to_array($records);
44
        }
45
46 4
        $json = @json_encode($records, $options, 2);
47 4
        if (JSON_ERROR_NONE === json_last_error()) {
48 2
            return $json;
49
        }
50
51 2
        throw new RuntimeException(json_last_error_msg());
52
    }
53
}
54