/** * 格式化属性值 * 可以通过重载此方法实现自定义格式化逻辑 * * @param string $key 属性名 * @param mixed $value 属性值 * @param array $attribute 属性定义信息 * @return mixed 格式化过后的值 */ protected function normalize($key, $value, array $attribute) { return Type::factory($attribute['type'])->normalize($value, $attribute); }
/** * 修改属性值并把被修改的属性标记为被修改过的状态 * * @param string $key * @param mixed $value * @param array $attribute * @return void */ protected final function change($key, $value, array $attribute = null) { $attribute = $attribute ?: static::getMapper()->getAttribute($key); $type = Type::factory($attribute['type']); if (array_key_exists($key, $this->values)) { if ($value === $this->values[$key]) { return; } elseif ($type->isNull($value) && $type->isNull($this->values[$key])) { return; } } elseif ($type->isNull($value) && $attribute['allow_null']) { return; } $this->values[$key] = $value; $this->dirty[$key] = true; }
/** * 把Data实例内的数据,转换为适用于存储的格式 * * @param Data $data * @param array [$options] * @return array */ public function unpack(Data $data, array $options = null) { $defaults = ['dirty' => false]; $options = $options ? array_merge($defaults, $options) : $defaults; $attributes = $this->getAttributes(); $record = []; foreach ($data->pick(array_keys($attributes)) as $key => $value) { if ($options['dirty'] && !$data->isDirty($key)) { continue; } if ($value !== null) { $attribute = $attributes[$key]; $value = Type::factory($attribute['type'])->store($value, $attribute); } $record[$key] = $value; } return $record; }