Completed
Push — 2.x ( 6c47ee...c394f3 )
by Aleksei
24s queued 15s
created

Jsoner::toJson()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 6
nc 3
nop 3
dl 0
loc 13
rs 10
c 1
b 1
f 0
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\BuilderException;
15
16
/**
17
 * Helper that can be used to convert values into JSON strings and validate them.
18
 */
19
final class Jsoner
20
{
21
    /**
22
     * @param bool $encode Encode the value into JSON.
23
     * @param bool $validate Check that $value is a valid JSON string if the $encode parameter is false.
24
     *
25
     * @throws BuilderException|\JsonException
26
     */
27
    public static function toJson(mixed $value, bool $encode = true, bool $validate = true): string
28
    {
29
        if ($encode) {
30
            return \json_encode($value, \JSON_UNESCAPED_UNICODE|\JSON_THROW_ON_ERROR);
31
        }
32
33
        $result = (string)$value;
34
35
        if ($validate && !\json_validate($result)) {
36
            throw new BuilderException('Invalid JSON value.');
37
        }
38
39
        return $result;
40
    }
41
}
42