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

JsonConverter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
wmc 3
lcom 0
cbo 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A convert() 0 15 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
     * 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