Cast.php
1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* LearnDash Casting class.
*
* @since 4.7.0
*
* @package LearnDash\Core
*/
namespace LearnDash\Core\Utilities;
/**
* A helper class to provide easier ways to cast.
*
* @since 4.7.0
*/
class Cast {
/**
* Casts a value to a string if possible or returns an empty string.
*
* @since 4.7.0
*
* @param mixed $value The value to cast.
*
* @return string
*/
public static function to_string( $value ): string {
if ( is_string( $value ) ) {
return $value;
}
if ( ! is_scalar( $value ) ) {
return '';
}
return strval( $value );
}
/**
* Casts a value to a int if possible or returns an empty string.
*
* @since 4.7.0
*
* @param mixed $value The value to cast.
*
* @return int
*/
public static function to_int( $value ): int {
if ( is_int( $value ) ) {
return $value;
}
if ( ! is_scalar( $value ) ) {
return 0;
}
return intval( $value );
}
/**
* Casts a value to a float if possible or returns an empty string.
*
* @since 4.7.0
*
* @param mixed $value The value to cast.
*
* @return float
*/
public static function to_float( $value ): float {
if ( is_float( $value ) ) {
return $value;
}
if ( ! is_scalar( $value ) ) {
return 0.0;
}
return floatval( $value );
}
/**
* Casts a value to a bool if possible or returns an empty string.
*
* @since 4.7.0
*
* @param mixed $value The value to cast.
*
* @return bool
*/
public static function to_bool( $value ): bool {
if ( is_bool( $value ) ) {
return $value;
}
if ( ! is_scalar( $value ) ) {
return false;
}
return boolval( $value );
}
}