DataSetNormalizer::normalize()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 4
nop 1
dl 0
loc 15
ccs 0
cts 0
cp 0
crap 20
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Helper;
6
7
use Yiisoft\Validator\DataSet\ArrayDataSet;
8
use Yiisoft\Validator\DataSet\ObjectDataSet;
9
use Yiisoft\Validator\DataSet\SingleValueDataSet;
10
use Yiisoft\Validator\DataSetInterface;
11
12
use function is_array;
13
use function is_object;
14
15
/**
16
 * A helper class used to normalize different types of validated data to a data set ({@see DataSetInterface}).
17 822
 */
18
final class DataSetNormalizer
19 822
{
20 79
    /**
21
     * Normalizes different types of validated data to a data set:
22
     *
23 748
     * - If {@see $data} is already a data set, it will be left as is.
24 42
     * - An object is normalized to {@see ObjectDataSet}.
25
     * - An array is normalized to {@see ArrayDataSet}.
26
     * - Everything else is normalized to {@see SingleValueDataSet}.
27 710
     *
28 166
     * In order to prevent mapping objects and arrays to corresponding data sets, wrap them with
29
     * {@see SingleValueDataSet} explicitly or use a custom data set ({@see DataSetInterface}).
30
     *
31 573
     * @param mixed $data Raw validated data of any type.
32
     *
33
     * @return DataSetInterface Data set instance.
34
     */
35
    public static function normalize(mixed $data): DataSetInterface
36
    {
37
        if ($data instanceof DataSetInterface) {
38
            return $data;
39
        }
40
41
        if (is_object($data)) {
42
            return new ObjectDataSet($data);
43
        }
44
45
        if (is_array($data)) {
46
            return new ArrayDataSet($data);
47
        }
48
49
        return new SingleValueDataSet($data);
50
    }
51
}
52