ValueCaster::fromJson()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
ccs 0
cts 0
cp 0
crap 2
1
<?php
2
3
namespace ByTIC\DataObjects;
4
5
use Carbon\Carbon;
6
use Carbon\CarbonInterface;
7
use DateTime;
8
use DateTimeInterface;
9
10
/**
11
 * Class ValueCaster
12
 * @package ByTIC\DataObjects
13
 */
14
class ValueCaster
15
{
16
    /**
17
     * The built-in, primitive cast types
18
     *
19
     * @var array
20
     */
21
    public static $primitiveTypes = [
22
        'array',
23
        'bool',
24
        'boolean',
25
        'collection',
26
        'custom_datetime',
27
        'date',
28
        'datetime',
29
        'decimal',
30
        'double',
31
        'float',
32
        'int',
33
        'integer',
34
        'json',
35
        'object',
36
        'real',
37
        'string',
38
        'timestamp',
39
    ];
40 1
41
    public static function as($value, string $type)
42 1
    {
43 1
        switch ($type) {
44 1
            case 'int':
45
            case 'integer':
46
                return (int)$value;
47 1
48 1
            case 'real':
49 1
            case 'float':
50
            case 'double':
51
                return static::asFloat($value);
52 1
53
            case 'decimal':
54
                return static::asDecimal($value);
55 1
56 1
            case 'string':
57
            case 'str':
58
                return static::asString($value);
59 1
60 1
            case 'bool':
61
            case 'boolean':
62
                return (bool) $value;
63 1
64
            case 'date':
65
                return static::asDate($value);
66 1
67
            case 'datetime':
68 1
            case 'custom_datetime':
69
                return static::asDateTime($value);
70
71
            case 'timestamp':
72
                return static::asTimestamp($value);
0 ignored issues
show
Bug introduced by
The method asTimestamp() does not exist on ByTIC\DataObjects\ValueCaster. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
                return static::/** @scrutinizer ignore-call */ asTimestamp($value);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
74
75
            case 'object':
76
                return static::fromJson($value, true);
77
78
            case 'array':
79
            case 'json':
80
                return static::fromJson($value);
81
        }
82
    }
83
84
    /**
85
     * Cast given value to a string
86
     *
87
     * @param mixed $value
88
     *
89
     * @return string
90
     */
91
    public static function asString($value): string
92
    {
93
        return (string)$value;
94
    }
95
96
    /**
97
     * Cast given value to a string
98
     *
99
     * @param mixed $value
100
     *
101
     * @return string
102
     */
103
    public static function asInteger($value): string
104
    {
105
        return (int)$value;
106
    }
107
108
    /**
109
     * Decode the given float.
110
     *
111
     * @param  mixed  $value
112
     * @return mixed
113
     */
114
    public static function asFloat($value)
115
    {
116
        switch ((string) $value) {
117
            case 'Infinity':
118
                return INF;
119
            case '-Infinity':
120
                return -INF;
121
            case 'NaN':
122
                return NAN;
123
            default:
124
                return (float) $value;
125
        }
126
    }
127
128
    /**
129
     * Return a decimal as string.
130
     *
131
     * @param  float  $value
132
     * @param  int  $decimals
133
     * @return string
134
     */
135
    public static function asDecimal($value, $decimals = 3)
136
    {
137
        return number_format($value, $decimals, '.', '');
138
    }
139
140
    /**
141
     * Cast given value to a DateTime instance
142
     *
143
     * @param string|null $value
144
     *
145
     * @return Carbon|DateTimeInterface
146
     */
147 1
    public static function asDate($value)
148
    {
149
        $date = static::asDateTime($value);
150
        if ($date === null) {
151
            return null;
152 1
        }
153 1
        return $date->startOfDay();
154
    }
155
156
    /**
157
     * @param $value
158
     * @return ?DateTime
159 1
     */
160
    public static function asDateTime($value): ?DateTime
161
    {
162
        if (empty($value)) {
163
            return null;
164
        }
165
        // If this value is already a Carbon instance, we shall just return it as is.
166
        // This prevents us having to re-instantiate a Carbon instance when we know
167
        // it already is one, which wouldn't be fulfilled by the DateTime check.
168
        if ($value instanceof CarbonInterface) {
169 1
            return Carbon::instance($value);
170
        }
171
172
        // If the value is already a DateTime instance, we will just skip the rest of
173 1
        // these checks since they will be a waste of time, and hinder performance
174
        // when checking the field. We will just return the DateTime right away.
175
        if ($value instanceof DateTimeInterface) {
176
            return Carbon::parse(
177
                $value->format('Y-m-d H:i:s.u'),
178
                $value->getTimezone()
179
            );
180
        }
181
182
        // If this value is an integer, we will assume it is a UNIX timestamp's value
183
        // and format a Carbon object from this timestamp. This allows flexibility
184
        // when defining your date fields as they might be UNIX timestamps here.
185
        if (is_numeric($value)) {
186
            return Carbon::createFromTimestamp($value);
187
        }
188
189
        $date = Carbon::parse($value);
190
        if ($date->year < 1) {
191
            return null;
192
        }
193
194
        return $date;
195
    }
196
197
    /**
198
     * Decode the given JSON back into an array or object.
199
     *
200
     * @param string $value
201
     * @param bool $asObject
202
     * @return mixed
203
     */
204
    public static function fromJson($value, $asObject = false)
205
    {
206
        return json_decode($value, !$asObject);
207
    }
208
209
    /**
210
     * @param $value
211
     * @return false|string
212
     */
213
    public static function asJson($value)
214
    {
215
        return json_encode($value);
216
    }
217
}
218