31
31
* @package doganoo\PHPUtil\Util
32
32
*/
33
33
class ClassUtil {
34
+
34
35
/**
35
36
* ClassUtil constructor.
36
37
*/
@@ -45,13 +46,30 @@ private function __construct() {
45
46
* @throws \ReflectionException
46
47
*/
47
48
public static function getClassName ($ object ): ?string {
48
- if (null === $ object ) {
49
+ $ validObject = ClassUtil::isValidObject ($ object );
50
+ if (!$ validObject ) {
49
51
return null ;
50
52
}
53
+ return (new \ReflectionClass ($ object ))->getName ();
54
+ }
55
+
56
+ /**
57
+ * validates an object. $object has to be:
58
+ *
59
+ * 1. not null
60
+ * 2. an object verified by \is_object()
61
+ *
62
+ * @param $object
63
+ * @return bool
64
+ */
65
+ private static function isValidObject ($ object ): bool {
66
+ if (null === $ object ) {
67
+ return false ;
68
+ }
51
69
if (!\is_object ($ object )) {
52
- return null ;
70
+ return false ;
53
71
}
54
- return ( new \ ReflectionClass ( $ object ))-> getName () ;
72
+ return true ;
55
73
}
56
74
57
75
/**
@@ -84,4 +102,29 @@ public static function isSerialized(string $string): bool {
84
102
}
85
103
}
86
104
105
+ /**
106
+ * returns all properties of an object
107
+ *
108
+ * TODO let caller define the visibility
109
+ *
110
+ * @param $object
111
+ * @param bool $asString
112
+ * @return null|\ReflectionProperty[]|string
113
+ * @throws \ReflectionException
114
+ */
115
+ public static function getAllProperties ($ object , bool $ asString = true ) {
116
+ $ validObject = ClassUtil::isValidObject ($ object );
117
+ if (!$ validObject ) {
118
+ return null ;
119
+ }
120
+ $ reflectionClass = new \ReflectionClass ($ object );
121
+ $ properties = $ reflectionClass ->getProperties ();
122
+
123
+ if ($ asString ) {
124
+ return ArrayUtil::arrayToString ($ properties );
125
+ } else {
126
+ return $ properties ;
127
+ }
128
+ }
129
+
87
130
}
0 commit comments