/**
* @param $entity
* @param \Blast\Orm\Entity\DefinitionInterface|null $definition
* @return Definition
*/
private function transformEntityToDefinition($entity, $definition = null)
{
// find definition class in entity by property or method
$definition = $this->loadDefinitionFromEntity($entity, $definition);
$reflection = Support::getCachedReflectionClass($entity, $this->getReflectionCache());
$configuration = $definition->getConfiguration();
// mapper is a dependency for all other entity services
// fetch mapper first
if ($reflection->hasMethod('mapper')) {
$mapperMethod = $reflection->getMethod('mapper');
if ($mapperMethod->isStatic() && $mapperMethod->isPublic()) {
$configuration['mapper'] = $mapperMethod->invokeArgs($entity, [$entity]);
}
}
//update configuration with mapper
$configuration = $definition->setConfiguration($configuration)->getConfiguration();
foreach ($configuration as $key => $value) {
//ignore entity or mapper
if (in_array($key, ['entity', 'mapper'])) {
continue;
}
if ($reflection->hasMethod($key)) {
$method = $reflection->getMethod($key);
if ($method->isPublic() && $method->isStatic()) {
$value = $method->invokeArgs($entity, [$entity, $definition->getMapper()]);
}
} else {
$value = is_callable($value) ? call_user_func_array($value, [$entity, $definition->getMapper()]) : $value;
}
$configuration[$key] = $value;
}
$configuration['entityClassName'] = $reflection->getName();
$configuration['entityShortName'] = $reflection->getShortName();
// fetch table name from table property
if ($reflection->hasProperty('table')) {
$reflectionProperty = $reflection->getProperty('table');
if ($reflectionProperty->isStatic()) {
$configuration['tableName'] = $reflectionProperty->getValue($entity);
}
}
// fetch table name from table method
if ($reflection->hasMethod('table')) {
$reflectionMethod = $reflection->getMethod('table');
if ($reflectionMethod->isStatic()) {
$configuration['tableName'] = $reflectionMethod->invoke($entity);
}
}
$definition->setConfiguration($configuration);
// set table name from reflection short name
// if table name is unknown or FQCN and if
// entity is no ArrayObject
if ((empty($definition->getTableName()) || class_exists($definition->getTableName())) && !$definition->getEntity() instanceof \ArrayObject) {
$configuration['tableName'] = Inflector::pluralize(Inflector::tableize($configuration['entityShortName']));
}
return $definition->setConfiguration($configuration);
}