Passed
Push — master ( bd10da...d5e00b )
by Irfaq
14:58
created

Formatter::trunicateNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Transmission;
4
5
use Carbon\CarbonInterval;
6
use Illuminate\Support\Carbon;
7
8
/**
9
 * Formatter
10
 */
11
class Formatter
12
{
13
    /** Used by formatBytes() modes */
14
    const UNITS_MODE_DECIMAL = 0;
15
    const UNITS_MODE_BINARY = 1;
16
    /** Speed */
17
    const SPEED_KBPS = 1000;
18
19
    /**
20
     * Formats bytes into a human readable string if $format is true, otherwise return $bytes as is.
21
     *
22
     * @param int  $bytes
23
     * @param bool $format Should we suffix symbol? Default: true.
24
     * @param int  $mode   Should we calculate in binary/speed mode? Default: decimal.
25
     *
26
     * @return string
27
     */
28
    public static function formatBytes(int $bytes, bool $format = true, int $mode = 0): string
29
    {
30
        if (!$format) {
31
            return $bytes;
32
        }
33
34
        switch ($mode) {
35
            case static::UNITS_MODE_BINARY: // Binary (Used with memory size formating)
36
                $base = 1024;
37
                $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
38
                break;
39
            default: // Decimal (Disk space)
40
                $base = 1000;
41
                $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
42
                break;
43
        }
44
45
        $i = 0;
46
47
        while ($bytes > $base) {
48
            $bytes /= $base;
49
            $i++;
50
        }
51
52
        return round($bytes, 2) . ' ' . $units[$i];
53
    }
54
55
    /**
56
     * Speed Bps.
57
     *
58
     * @param $Bps
59
     *
60
     * @return string
61
     */
62
    public static function speedBps($Bps)
63
    {
64
        return static::speed(static::bpsToKBps($Bps));
65
    }
66
67
    /**
68
     * Bps to KBps.
69
     *
70
     * @param $Bps
71
     *
72
     * @return float
73
     */
74
    public static function bpsToKBps($Bps)
75
    {
76
        return floor($Bps / static::SPEED_KBPS);
77
    }
78
79
    /**
80
     * Format KBps to Data-rate units.
81
     *
82
     * @param $KBps
83
     *
84
     * @return string
85
     */
86
    public static function speed($KBps)
87
    {
88
        $speed = $KBps;
89
90
        if ($speed <= 999.95) { // 0 KBps to 999 K
91
            return static::trunicateNumber($speed, 0) . ' KB/s';
92
        }
93
94
        $speed /= static::SPEED_KBPS;
95
96
        if ($speed <= 99.995) { // 1 M to 99.99 M
97
            return static::trunicateNumber($speed, 2) . ' MB/s';
98
        }
99
        if ($speed <= 999.95) { // 100 M to 999.9 M
100
            return static::trunicateNumber($speed, 1) . ' MB/s';
101
        }
102
103
        // insane speeds
104
        $speed /= static::SPEED_KBPS;
105
106
        return static::trunicateNumber($speed, 2) . ' GB/s';
107
    }
108
109
    /**
110
     * Trunicate a number to the given decimal points.
111
     *
112
     * @param string $number
113
     * @param int    $decimals
114
     *
115
     * @return string
116
     */
117
    public static function trunicateNumber($number, int $decimals = 2)
118
    {
119
        return bcdiv($number, 1, $decimals);
120
    }
121
122
    /**
123
     * Cast an attribute to a native PHP type.
124
     *
125
     * @param mixed  $value
126
     * @param string $type
127
     *
128
     * @return mixed
129
     */
130
    public static function castAttribute($type, $value)
131
    {
132
        if (is_null($value)) {
133
            return $value;
134
        }
135
136
        switch ($type) {
137
            case 'collection':
138
                return collect(is_array($value) ? $value : (new static)->fromJson($value));
139
            case 'interval':
140
                return $value < 1 ? -1 : CarbonInterval::seconds($value)->cascade();
0 ignored issues
show
Bug Best Practice introduced by
The method Carbon\CarbonInterval::seconds() is not static, but was called statically. ( Ignorable by Annotation )

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

140
                return $value < 1 ? -1 : CarbonInterval::/** @scrutinizer ignore-call */ seconds($value)->cascade();
Loading history...
141
            case 'date':
142
                return (new static)->asDate($value);
143
            case 'datetime':
144
                return (new static)->asDateTime($value);
145
            case 'timestamp':
146
                return (new static)->asTimestamp($value);
147
            case 'size':
148
                return static::formatBytes($value);
149
            case 'memory':
150
                return static::formatBytes($value, true, static::UNITS_MODE_BINARY);
151
            case 'datarate':
152
                return static::speedBps($value);
153
            default:
154
                return $value;
155
        }
156
    }
157
158
    /**
159
     * Encode the given value as JSON.
160
     *
161
     * @param  mixed $value
162
     *
163
     * @return string
164
     */
165
    protected function asJson($value)
166
    {
167
        return json_encode($value);
168
    }
169
170
    /**
171
     * Decode the given JSON back into an array or object.
172
     *
173
     * @param  string $value
174
     * @param  bool   $asObject
175
     *
176
     * @return mixed
177
     */
178
    protected function fromJson($value, $asObject = false)
179
    {
180
        return json_decode($value, !$asObject);
181
    }
182
183
    /**
184
     * Return a timestamp as DateTime object with time set to 00:00:00.
185
     *
186
     * @param  mixed $value
187
     *
188
     * @return \Illuminate\Support\Carbon
189
     */
190
    protected function asDate($value)
191
    {
192
        return $this->asDateTime($value)->startOfDay();
193
    }
194
195
    /**
196
     * Return a timestamp as DateTime object.
197
     *
198
     * @param  mixed $value
199
     *
200
     * @return \Illuminate\Support\Carbon
201
     */
202
    protected function asDateTime($value)
203
    {
204
        // If this value is already a Carbon instance, we shall just return it as is.
205
        // This prevents us having to re-instantiate a Carbon instance when we know
206
        // it already is one, which wouldn't be fulfilled by the DateTime check.
207
        if ($value instanceof Carbon) {
208
            return $value;
209
        }
210
211
        // If this value is an integer, we will assume it is a UNIX timestamp's value
212
        // and format a Carbon object from this timestamp. This allows flexibility
213
        // when defining your date fields as they might be UNIX timestamps here.
214
        if (is_numeric($value)) {
215
            return Carbon::createFromTimestamp($value);
216
        }
217
218
        return $value;
219
    }
220
221
    /**
222
     * Return a timestamp as unix timestamp.
223
     *
224
     * @param  mixed $value
225
     *
226
     * @return int
227
     */
228
    protected function asTimestamp($value)
229
    {
230
        return $this->asDateTime($value)->getTimestamp();
231
    }
232
}