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

Jsoner::toJson()   B

Complexity

Conditions 11
Paths 21

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 11
eloc 7
c 1
b 1
f 0
nc 21
nop 3
dl 0
loc 13
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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