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: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118:
<?php
namespace MvcCore\Ext\Models\Db\Model;
trait Parsers {
protected static function parseToTypes ($rawValue, $typesString, $formatArgs = []) {
$targetTypeValue = NULL;
$value = $rawValue;
foreach ($typesString as $typeString) {
if (substr($typeString, -2, 2) === '[]') {
if (!is_array($value)) {
$value = trim(strval($rawValue));
$value = $value === '' ? [] : explode(',', $value);
}
$arrayItemTypeString = substr($typeString, 0, strlen($typeString) - 2);
$targetTypeValue = [];
$conversionResult = TRUE;
foreach ($value as $key => $item) {
list(
$conversionResultLocal, $targetTypeValueLocal
) = static::parseToType($item, $arrayItemTypeString, $formatArgs);
if ($conversionResultLocal) {
$targetTypeValue[$key] = $targetTypeValueLocal;
} else {
$conversionResult = FALSE;
break;
}
}
} else {
list(
$conversionResult, $targetTypeValue
) = static::parseToType($rawValue, $typeString, $formatArgs);
}
if ($conversionResult) {
$value = $targetTypeValue;
break;
}
}
return $value;
}
protected static function parseToType ($rawValue, $typeStr, $formatArgs = []) {
$conversionResult = FALSE;
$typeStr = trim($typeStr, '\\');
if ($typeStr == 'DateTime') {
if (!($rawValue instanceof \DateTime)) {
if ($formatArgs !== NULL && count($formatArgs) > 0) {
$dateTime = static::parseToDateTime($rawValue, $formatArgs);
} else {
$dateTime = static::parseToDateTimeDefault($rawValue, '+Y-m-d H:i:s');
}
if ($dateTime instanceof \DateTime) {
$rawValue = $dateTime;
$conversionResult = TRUE;
}
}
} else {
if (settype($rawValue, $typeStr))
$conversionResult = TRUE;
}
return [$conversionResult, $rawValue];
}
protected static function parseToDateTime ($rawValue, $formatArgs) {
$dateTimeFormat = $formatArgs[0];
if (is_numeric($rawValue)) {
$rawValueStr = str_replace(['+','-','.'], '', (string) $rawValue);
$secData = mb_substr($rawValueStr, 0, 10);
$dateTimeStr = date($dateTimeFormat, intval($secData));
if (strlen($rawValueStr) > 10)
$dateTimeStr .= '.' . mb_substr($rawValueStr, 10);
} else {
$dateTimeStr = (string) $rawValue;
}
if (isset($formatArgs[1])) {
$timeZone = new \DateTimeZone((string) $formatArgs[1]);
$dateTime = \date_create_from_format($dateTimeFormat, $dateTimeStr, $timeZone);
} else {
$dateTime = \date_create_from_format($dateTimeFormat, $dateTimeStr);
}
return $dateTime;
}
}