Completed
Push — master ( 147747...e61ddd )
by ignace nyamagana
23:03 queued 02:55
created

JsonConverter::options()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 1
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
     * 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, 'The options must be a positive integer or 0');
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);
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