Created
March 21, 2018 09:51
-
-
Save misaon/f922275046a8e7fcb7eb7cfbe36c7222 to your computer and use it in GitHub Desktop.
Fetch pairs from entity object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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