1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92:
<?php
namespace MvcCore\Ext\Models\Db\Model;
trait Connection {
public static function GetConnection ($connectionNameOrConfig = NULL, $strict = TRUE) {
if ($connectionNameOrConfig === NULL) {
list(,$callerInfo) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
if (!isset($callerInfo['class']))
throw new \RuntimeException(
"[".get_called_class()."] Database static connection getter has to be called from class only."
);
try {
$getMetaDataMethod = new \ReflectionMethod(ltrim($callerInfo['class']), 'getMetaData');
$getMetaDataMethod->setAccessible(TRUE);
list(, $connAttrArgs) = $getMetaDataMethod->invokeArgs(
NULL, [0, [\MvcCore\Ext\Models\Db\Model\IConstants::METADATA_CONNECTIONS]]
);
if ($connAttrArgs > 0)
$connectionNameOrConfig = $connAttrArgs[0];
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
}
$connectionName = (is_string($connectionNameOrConfig) || is_int($connectionNameOrConfig))
? $connectionNameOrConfig
: static::resolveConnectionName($connectionNameOrConfig, $strict);
if (isset(self::$connections[$connectionName]))
return self::$connections[$connectionName];
$cfg = static::GetConfig($connectionName);
if ($cfg === NULL) throw new \InvalidArgumentException(
"[".get_called_class()."] No connection found under given name/index: `{$connectionName}`."
);
$sysCfgProps = static::$sysConfigProperties;
$sysConfigClassProp = $sysCfgProps['class'];
if (!isset($cfg->{$sysConfigClassProp})) {
$providerDriverName = static::$providerDriverName;
if ($providerDriverName !== NULL) {
if ($providerDriverName === $cfg->driver) {
$cfg = (object) array_merge([], (array) $cfg);
$cfg->{$sysConfigClassProp} = static::$providerConnectionClass;
} else {
throw new \RuntimeException(
"[".get_called_class()."] Default connection has different driver ".
"name `{$cfg->driver}` than current class is extended from."
);
}
}
}
$connection = static::connect($cfg);
self::$connections[$connectionName] = $connection;
return $connection;
}
}