Typecast a single column value based on the model properties for that column

@param  string  $column	name of the column
@param  string  $value	value
@param  string  $settings	column settings from the model

@throws  InvalidContentType

@return  mixed
556077
public static function typecast($column, $value, $settings, $event_type	= 'before')
	{
		 // only on before_save, check if null is allowed
		if ($value === null)
		{
			 // only on before_save
			if ($event_type == 'before')
			{
				if (array_key_exists('null', $settings) and $settings['null'] === false)
				{
					// if a default is defined, return that instead
					if (array_key_exists('default', $settings))
					{
						return $settings['default'];
					}

					throw new InvalidContentType('The property "'.$column.'" cannot be NULL.');
				}
			}
			return $value;
		}

		// no datatype given
		if (empty($settings['data_type']))
		{
			return $value;
		}

		// get the data type for this column
		$data_type = $settings['data_type'];

		// is this a base data type?
		if ( ! isset(static::$type_methods[$data_type]))
		{
			// no, can we map it to one?
			if (isset(static::$type_mappings[$data_type]))
			{
				// yes, so swap it for a base data type
				$data_type = static::$type_mappings[$data_type];
			}
			else
			{
				// can't be mapped, check the regexes
				foreach (static::$regex_methods as $match => $methods)
				{
					// fetch the method
					$method = ! empty($methods[$event_type]) ? $methods[$event_type] : false;

					if ($method)
					{
						if (preg_match_all($match, $data_type, $matches) > 0)
						{
							$value = call_user_func($method, $value, $settings, $matches);
						}
					}
				}
				return $value;
			}
		}

		// fetch the method
		$method = ! empty(static::$type_methods[$data_type][$event_type]) ? static::$type_methods[$data_type][$event_type] : false;

		// if one was found, call it
		if ($method)
		{
			$value = call_user_func($method, $value, $settings);
		}

		return $value;
	}
374729
protected function evalSwitchTypeValue($record, $column, $value)
    {
        $contents = '';

        if ($value) {
            $contents = Lang::get('backend::lang.list.column_switch_true');
        }
        else {
            $contents = Lang::get('backend::lang.list.column_switch_false');
        }

        return $contents;
    }
359867
protected function convertValueForColumn($value, ColumnMap $colMap)
    {
        if ($colMap->getType() == 'OBJECT' && is_object($value)) {
            if (is_array($value)) {
                $value = array_map('serialize', $value);
            } else {
                $value = serialize($value);
            }
        } elseif ('ARRAY' === $colMap->getType() && is_array($value)) {
            $value = '| ' . implode(' | ', $value) . ' |';
        } elseif (PropelTypes::ENUM === $colMap->getType() && !is_null($value)) {
            if (is_array($value)) {
                $value = array_map([$colMap, 'getValueSetKey'], $value);
            } else {
                $value = $colMap->getValueSetKey($value);
            }
        } elseif ($colMap->isSetType() && !is_null($value)) {
            try {
                $value = SetColumnConverter::convertToInt($value, $colMap->getValueSet());
            } catch (SetColumnConverterException $e) {
                throw new PropelException(sprintf('Value "%s" is not accepted in this set column', $e->getValue()), $e->getCode(), $e);
            }
        }

        return $value;
    }
1289513
protected function castSetting($key, $value)
    {
        if (is_null($value)) {
            return $value;
        }

        if (!in_array($key, $this->notBooleans) && in_array($value, ['0', '1'])) {
            return (bool) $value;
        }

        return $value;
    }
353116
protected function processArrayValue(
        array $value,
        array $settings,
        /*# bool */ $between = false
    )/*# : string */ {
        if ($between) {
            $v1 = $this->processValue($value[0], $settings);
            $v2 = $this->processValue($value[1], $settings);
            return $v1 . ' AND ' . $v2;
        } else {
            $result = [];
            foreach ($value as $val) {
                $result[] = $this->processValue($val, $settings);
            }
            return '(' . join(', ', $result) . ')';
        }
    }
1140080
public function _typecastLoadField(Field $f, $value)
    {
        // LOB fields return resource stream
        if (is_resource($value)) {
            $value = stream_get_contents($value);
        }

        // work only on copied value not real one !!!
        $v = is_object($value) ? clone $value : $value;

        switch ($f->type) {
        case 'string':
        case 'text':
            // do nothing - it's ok as it is
            break;
        case 'integer':
            $v = (int) $v;
            break;
        case 'float':
            $v = (float) $v;
            break;
        case 'money':
            $v = round($v, 4);
            break;
        case 'boolean':
            if (isset($f->enum) && is_array($f->enum)) {
                if (isset($f->enum[0]) && $v == $f->enum[0]) {
                    $v = false;
                } elseif (isset($f->enum[1]) && $v == $f->enum[1]) {
                    $v = true;
                } else {
                    $v = null;
                }
            } elseif ($v === '') {
                $v = null;
            } else {
                $v = (bool) $v;
            }
            break;
        case 'date':
        case 'datetime':
        case 'time':
            $dt_class = isset($f->dateTimeClass) ? $f->dateTimeClass : 'DateTime';
            $tz_class = isset($f->dateTimeZoneClass) ? $f->dateTimeZoneClass : 'DateTimeZone';

            if (is_numeric($v)) {
                $v = new $dt_class('@'.$v);
            } elseif (is_string($v)) {
                // ! symbol in date format is essential here to remove time part of DateTime - don't remove, this is not a bug
                $format = ['date' => '+!Y-m-d', 'datetime' => '+!Y-m-d H:i:s', 'time' => '+!H:i:s'];
                $format = $f->persist_format ?: $format[$f->type];

                // datetime only - set from persisting timezone
                if ($f->type == 'datetime' && isset($f->persist_timezone)) {
                    $v = $dt_class::createFromFormat($format, $v, new $tz_class($f->persist_timezone));
                    if ($v === false) {
                        throw new Exception(['Incorrectly formatted datetime', 'format' => $format, 'value' => $value, 'field' => $f]);
                    }
                    $v->setTimeZone(new $tz_class(date_default_timezone_get()));
                } else {
                    $v = $dt_class::createFromFormat($format, $v);
                    if ($v === false) {
                        throw new Exception(['Incorrectly formatted date/time', 'format' => $format, 'value' => $value, 'field' => $f]);
                    }
                }

                // need to cast here because DateTime::createFromFormat returns DateTime object not $dt_class
                // this is what Carbon::instance(DateTime $dt) method does for example
                if ($dt_class != 'DateTime') {
                    $v = new $dt_class($v->format('Y-m-d H:i:s.u'), $v->getTimeZone());
                }
            }
            break;
        case 'array':
            // don't decode if we already use some kind of serialization
            $v = $f->serialize ? $v : $this->jsonDecode($f, $v, true);
            break;
        case 'object':
            // don't decode if we already use some kind of serialization
            $v = $f->serialize ? $v : $this->jsonDecode($f, $v, false);
            break;
        }

        return $v;
    }
322031
public function setSetting($section, $key, $value, $type = null): bool
    {
        $model = static::findOne(['section' => $section, 'key' => $key]);

        if (empty($model)) {
            $model = new static();
        }

        $model->section = $section;
        $model->key = $key;
        $model->value = strval($value);

        if ($type !== null && ArrayHelper::keyExists($type, SettingType::getConstantsByValue())) {
            $model->type = $type;
        } else {
            $model->type = gettype($value);
        }

        return $model->save();
    }
64917
function encodeType($value, \Plasma\ColumnDefinitionInterface $column): \Plasma\Types\TypeExtensionResultInterface {
        $type = \gettype($value);
        if($type === 'double') {
            $type = 'float';
        }
        
        if($type === 'object') {
            $classes = \array_merge(
                array(\get_class($value)),
                \class_parents($value),
                \class_implements($value)
            );
            
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->classTypes as $key => $encoder) {
                if(\in_array($key, $classes, true)) {
                    return $encoder->encode($value, $column);
                }
            }
        }
        
        /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
        foreach($this->regularTypes as $key => $encoder) {
            if($type === $key) {
                return $encoder->encode($value, $column);
            }
        }
        
        if($this->enabledFuzzySearch) {
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->classTypes as $key => $encoder) {
                if($encoder->canHandleType($value, $column)) {
                    return $encoder->encode($value, $column);
                }
            }
            
            /** @var \Plasma\Types\TypeExtensionInterface  $encoder */
            foreach($this->regularTypes as $key => $encoder) {
                if($encoder->canHandleType($value, $column)) {
                    return $encoder->encode($value, $column);
                }
            }
        }
        
        throw new \Plasma\Exception('Unable to encode given value');
    }
484764
protected function typecastValue($value, $type)
    {
        if (is_scalar($type)) {
            if (is_object($value) && method_exists($value, '__toString')) {
                $value = $value->__toString();
            }

            switch ($type) {
                case self::TYPE_INTEGER:
                    return (int)$value;
                case self::TYPE_FLOAT:
                    return (float)$value;
                case self::TYPE_BOOLEAN:
                    return (bool)$value;
                case self::TYPE_STRING:
                    return (string)$value;
                case self::TYPE_JSON:
                    return is_string($value) ? $value : json_encode($value);
                case self::TYPE_IMPLODE:
                    return is_string($value) ? $value : (string)implode($this->delimiter, $value);
                case self::TYPE_SERIALIZE:
                    return is_string($value) ? $value : serialize($value);
                default:
                    throw new InvalidParamException("Unsupported type '{$type}'");
            }
        }

        return call_user_func($type, $value);
    }
1070704
private function cast(int $column, string $value)
    {
        switch ($this->fieldTypes[$column]) {
            case 16: // bool
                return $value === 't';

            case 20: // int8
            case 21: // int2
            case 23: // int4
            case 26: // oid
            case 27: // tid
            case 28: // xid
                return (int) $value;

            case 700: // real
            case 701: // double-precision
                return (float) $value;

            case 1000: // boolean[]
                return $this->parser->parse($value, function (string $value): bool {
                    return $value === 't';
                });

            case 1005: // int2[]
            case 1007: // int4[]
            case 1010: // tid[]
            case 1011: // xid[]
            case 1016: // int8[]
            case 1028: // oid[]
                return $this->parser->parse($value, function (string $value): int {
                    return (int) $value;
                });

            case 1021: // real[]
            case 1022: // double-precision[]
                return $this->parser->parse($value, function (string $value): float {
                    return (float) $value;
                });

            case 1020: // box[] (semi-colon delimited)
                return $this->parser->parse($value, null, ';');

            case 199:  // json[]
            case 629:  // line[]
            case 651:  // cidr[]
            case 719:  // circle[]
            case 775:  // macaddr8[]
            case 791:  // money[]
            case 1001: // bytea[]
            case 1002: // char[]
            case 1003: // name[]
            case 1006: // int2vector[]
            case 1008: // regproc[]
            case 1009: // text[]
            case 1013: // oidvector[]
            case 1014: // bpchar[]
            case 1015: // varchar[]
            case 1019: // path[]
            case 1023: // abstime[]
            case 1024: // realtime[]
            case 1025: // tinterval[]
            case 1027: // polygon[]
            case 1034: // aclitem[]
            case 1040: // macaddr[]
            case 1041: // inet[]
            case 1115: // timestamp[]
            case 1182: // date[]
            case 1183: // time[]
            case 1185: // timestampz[]
            case 1187: // interval[]
            case 1231: // numeric[]
            case 1263: // cstring[]
            case 1270: // timetz[]
            case 1561: // bit[]
            case 1563: // varbit[]
            case 2201: // refcursor[]
            case 2207: // regprocedure[]
            case 2208: // regoper[]
            case 2209: // regoperator[]
            case 2210: // regclass[]
            case 2211: // regtype[]
            case 2949: // txid_snapshot[]
            case 2951: // uuid[]
            case 3221: // pg_lsn[]
            case 3643: // tsvector[]
            case 3644: // gtsvector[]
            case 3645: // tsquery[]
            case 3735: // regconfig[]
            case 3770: // regdictionary[]
            case 3807: // jsonb[]
            case 3905: // int4range[]
            case 3907: // numrange[]
            case 3909: // tsrange[]
            case 3911: // tstzrange[]
            case 3913: // daterange[]
            case 3927: // int8range[]
            case 4090: // regnamespace[]
            case 4097: // regrole[]
                return $this->parser->parse($value);

            default:
                return $value;
        }
    }
872798
protected function validateDateTimeValue($value, $column)
    {
        $value = DateTimeHelper::makeCarbon($value, false);

        if (!$value instanceof Carbon) {
            throw new ApplicationException(Lang::get(
                'backend::lang.list.invalid_column_datetime',
                ['column' => $column->columnName]
            ));
        }

        return $value;
    }
845990
public function serialize($value) : string
    {
        if (!$value instanceof \DateTimeInterface) {
            throw InvalidValueException::valueDoesNotMatchType($this, $value);
        }

        return (string) $value->format($this->format);
    }
190837
public static function typecast(&$value, $type)
    {
        switch ($type) {
            case Validate::TYPE_INT:
            case Validate::TYPE_UINT:
                $value = intval($value);
                break;
            case Validate::TYPE_FLOAT:
                $value = floatval($value);
                break;
            case Validate::TYPE_DOUBLE:
                $value = doubleval($value);
                break;
            case Validate::TYPE_BOOLEAN:
                $value = boolval($value);
                break;
            case Validate::TYPE_UNIX_TIMESTAMP:
                //Add the timezone offset (in minutes)
                $value = intval($value) +
                    (\Phramework\Phramework::getTimezoneOffset()*60);
                break;
        }
    }
1183444
public function normalizeValue($type, $value)
    {
        if ($value === null) {
            return null;
        }

        if ($type === 'string') {
            return is_string($value) ? $value : (string)$value;
        } elseif ($type === 'int') {
            return is_int($value) ? $value : (int)$value;
        } elseif ($type === 'float') {
            return is_float($value) ? $value : (float)$value;
        } elseif ($type === 'objectid') {
            return is_scalar($type) ? new ObjectID($value) : $value;
        } elseif ($type === 'bool') {
            return is_bool($value) ? $value : (bool)$value;
        } elseif ($type === 'array') {
            return (array)$value;
        } else {
            throw new InvalidValueException(['`:model` model is not supported `:type` type', 'model' => static::class, 'type' => $type]);
        }
    }
823176
public static function to_type($value, string $type='', bool $flatten=false) {
		ref\cast::to_type($value, $type, $flatten);
		return $value;
	}
321678
function MapValue($value)
    {
        if ($value === null)
            return $value;
        
        if ($this->IsRelatedObject($value) || $this->IsDatabaseObject($value))
            return $value;
        
        else if (!is_object($value) && !is_array($value))
        {
            if ($this->relatedSchema)
                return $this->relatedSchema->CreateInstance($value);
            else
                return $this->type->FromDBString((string)$value);
        }

        //no more object types mappable.
        throw new \InvalidArgumentException('Invalid argument for fieldmapper. Object could not be mapped');
    }
1292024
public function setValue($value) {
        if ($value !== null) {
            if ($this->isIncremental() && ! is_numeric($value)) {
                throw new InvalidOptionValueException(s(
                    'Trying to set a non numeric value "%s" on incremental option "%s".',
                    get_type($value),
                    $this->getNameOrAlias()
                ));
            }

            if ($this->isBoolean() && ! is_bool($value)) {
                throw new InvalidOptionValueException(s(
                    'Trying to set a non boolean value "%s" on boolean option "%s".',
                    get_type($value),
                    $this->getNameOrAlias()
                ));
            }

            if ($this->isSingle() && ! is_scalar($value)) {
                throw new InvalidOptionValueException(s(
                    'Trying to set a non scalar value "%s" on option "%s" ' .
                    'that expects one scalar value.',
                    get_type($value),
                    $this->getNameOrAlias()
                ));
            }

            if ($this->isMultiple() && ! is_array($value)) {
                throw new InvalidOptionValueException(s(
                    'Trying to set a non array value "%s" on option "%s" ' .
                    'that expects multiple values.',
                    get_type($value),
                    $this->getNameOrAlias()
                ));
            }
        }

        $this->value = $value;

        return $this;
    }