Skip to content

Commit 421a65c

Browse files
committed
ClassUtil::getProperties() method
1 parent 143d4cd commit 421a65c

File tree

2 files changed

+47
-4
lines changed

2 files changed

+47
-4
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,6 @@
1515
}
1616
},
1717
"require": {
18-
"doganoo/php-algorithms": "^0.0.1"
18+
"doganoo/php-algorithms": "*"
1919
}
2020
}

src/Util/ClassUtil.php

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* @package doganoo\PHPUtil\Util
3232
*/
3333
class ClassUtil {
34+
3435
/**
3536
* ClassUtil constructor.
3637
*/
@@ -45,13 +46,30 @@ private function __construct() {
4546
* @throws \ReflectionException
4647
*/
4748
public static function getClassName($object): ?string {
48-
if (null === $object) {
49+
$validObject = ClassUtil::isValidObject($object);
50+
if (!$validObject) {
4951
return null;
5052
}
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+
}
5169
if (!\is_object($object)) {
52-
return null;
70+
return false;
5371
}
54-
return (new \ReflectionClass($object))->getName();
72+
return true;
5573
}
5674

5775
/**
@@ -84,4 +102,29 @@ public static function isSerialized(string $string): bool {
84102
}
85103
}
86104

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+
87130
}

0 commit comments

Comments
 (0)