Completed
Push — master ( a01c69...69ad17 )
by ignace nyamagana
06:25 queued 04:34
created

JsonConverter::preserveRecordOffset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
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 DOMDOcument object
22
 *
23
 * @package League.csv
24
 * @since   9.0.0
25
 * @author  Ignace Nyamagana Butera <[email protected]>
26
 */
27
class JsonConverter implements Converter
28
{
29
    use ConverterTrait;
30
31
    /**
32
     * json_encode options
33
     *
34
     * @var int
35
     */
36
    protected $options = 0;
37
38
    /**
39
     * json_encode depth
40
     *
41
     * @var int
42
     */
43
    protected $depth = 512;
44
45
    /**
46
     * Json encode Options
47
     *
48
     * @param int $options
49
     * @param int $depth
50
     *
51
     * @return self
52
     */
53 2
    public function options(int $options = 0, int $depth = 512): self
54
    {
55 2
        $clone = clone $this;
56 2
        $clone->options = $options;
57 2
        $clone->depth = $depth;
58
59 2
        return $clone;
60
    }
61
62
    /**
63
     * Convert an Record collection into a Json string
64
     *
65
     * @param array|Traversable $records the CSV records collection
66
     *
67
     * @return string
68
     */
69 4
    public function convert($records)
70
    {
71 4
        $records = $this->convertToUtf8($this->filterIterable($records, __METHOD__));
72 4
        if (!is_array($records)) {
73 4
            $records = iterator_to_array($records);
74
        }
75
76 4
        $json = @json_encode($records, $this->options, $this->depth);
77 4
        if (JSON_ERROR_NONE === json_last_error()) {
78 2
            return $json;
79
        }
80
81 2
        throw new RuntimeException(json_last_error_msg());
82
    }
83
}
84