Skip to content

Instantly share code, notes, and snippets.

@misaon
Created March 21, 2018 09:50
Show Gist options
  • Save misaon/dd2ac1337a6b8e1392d201731b58d876 to your computer and use it in GitHub Desktop.
Save misaon/dd2ac1337a6b8e1392d201731b58d876 to your computer and use it in GitHub Desktop.
Fetch pairs from entity object.
public function getPairs(array $source, string $key, string $value): array
{
$result = [];
$methodPrefixes = ['get', 'is'];
$methodName = function (string $prefix, string $column) {
return $prefix . Strings::firstUpper($column);
};
$getAllProperties = function ($class) {
$properties = [];
try {
$rc = new \ReflectionClass($class);
do {
$rp = [];
/* @var $p \ReflectionProperty */
foreach ($rc->getProperties() as $p) {
$p->setAccessible(true);
$rp[$p->getName()] = $p->getValue($class);
}
/** @noinspection SlowArrayOperationsInLoopInspection */
$properties = array_merge($rp, $properties);
} while ($rc = $rc->getParentClass());
} catch (\ReflectionException $e) {
}
return $properties;
};
foreach ($source as $entity) {
$entityProperties = $getAllProperties($entity);
if (isset($entityProperties[$key], $entityProperties[$value])) {
$keyMethodName = null;
$valueMethodName = null;
foreach ($methodPrefixes as $prefix) {
!method_exists($entity, $methodName($prefix, $key)) ?: $keyMethodName = $methodName($prefix, $key);
!method_exists($entity, $methodName($prefix, $value)) ?: $valueMethodName = $methodName($prefix, $value);
}
$result[$entity->{$keyMethodName}()] = $entity->{$valueMethodName}();
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment