Passed
Pull Request — 2.x (#135)
by
unknown
20:30
created

Jsoner   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 8
c 1
b 1
f 0
dl 0
loc 21
rs 10
wmc 11

1 Method

Rating   Name   Duplication   Size   Complexity  
B toJson() 0 13 11
1
<?php
2
3
/**
4
 * This file is part of Cycle ORM package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Driver;
13
14
use Cycle\Database\Exception\DriverException;
15
16
/**
17
 * Helper that allows to convert any value to JSON.
18
 */
19
final class Jsoner
20
{
21
    /**
22
     * @param bool $encode Encode the value into JSON.
23
     * @param bool $validate Checking the value that it is valid JSON.
24
     *
25
     * @throws \JsonException
26
     */
27
    public static function toJson(mixed $value, bool $encode = true, bool $validate = true): string
28
    {
29
        if (!$encode && $validate && \is_string($value) && !json_validate($value)) {
30
            throw new DriverException('Invalid JSON value.');
31
        }
32
33
        if ($encode && !$validate) {
34
            $value = \json_encode($value, \JSON_UNESCAPED_UNICODE|\JSON_THROW_ON_ERROR);
35
        }
36
37
        return $encode && $validate && (!\is_string($value) || !json_validate($value))
38
            ? \json_encode($value, \JSON_UNESCAPED_UNICODE|\JSON_THROW_ON_ERROR)
39
            : $value;
40
    }
41
}
42