ClosureExpressionVisitor, reflection for more readability.
So I went through the source multiple times and found the method "getObjectFieldValue" to be hard to read, as well as quite inefficient when using the method ArrayCollection::matching(), especially when it comes to string.
I do admit that as a beginner to PHP I did not understand all of it but I do believe myself to have moderate knowledge of it.
Anyways, my solution to this would be the following:
public static function getObjectFieldValue($object, $field)
{
$field = preg_replace_callback('/_(.?)/', function ($matches) {
return strtoupper($matches[1]);
}, $field);
if (is_array($object)) {
return $object[$field];
}
$reflection = is_object($object)
? new ReflectionObject($object)
: new ReflectionClass($object);
if ($reflection->implementsInterface(ArrayAccess::class)) {
return $reflection->getMethod('offsetGet')->invoke($reflection->newInstanceWithoutConstructor(), $field);
}
if ($reflection->hasProperty($field)) {
$property = $reflection->getProperty($field);
if ($property->isPrivate() || $property->isProtected()) {
$property->setAccessible(true);
}
return $property->getValue($reflection->newInstanceWithoutConstructor());
}
return static::getMethod($reflection, $reflection->newInstanceWithoutConstructor(), $field);
}
protected static function getMethod($reflection, $object, $field)
{
foreach (['is', 'get'] as $accessor) {
$method = sprintf('%s%s', $accessor, ucfirst($field));
if ($reflection->hasMethod($method)) {
return $reflection->getMethod($method)->invoke($object);
}
}
}
In case of a non- existent property, assume it to be a method. Did my best to following the old source to the best of my ability. However, I do suggest to allow it to first check the value of an element instead of having it assuming the $object to be an instance of something.
Example
$c = new ArrayCollection([
'username' => 'test'
]);
$criteria = new Project\Criteria\Criteria;
var_dump($c->matching($criteria->andWhere($criteria->expr()->contains('username', 'test'))));`
It would then check if the value of the element username matches the requested value, and then in case of match, return just that.
I will once again mention that my proficiency in PHP isn't very high and I'm sure that there are many ways to improve this and would like to have your honest opinion regarding my suggestion.
Friendly regards, Yelson.
@rgyelson could you please send a PR with your suggestions instead? It would be easier to look at things and even perform benchmarks if needed.