id = $id; } /** * Create from object or array * * @param $obj */ public function __construct($obj) { $b = objBag($obj); if (!$b->has('name')) throw new NotApplicableException('Missing name in column'); if (!$b->has('type')) throw new NotApplicableException('Missing type in column'); if ($b->name[0] == '_') { // global row ID throw new NotApplicableException("Column name can't start with underscore."); } if (!in_array($b->type, self::colTypes)) { throw new NotApplicableException("\"$b->type\" is not a valid column type."); } $this->id = $b->get('id', null); $this->name = $b->name; $this->type = $b->type; $this->title = $b->title ?: $b->name; } public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } throw new NotApplicableException("No such column property: $name"); } /** * @return array with keys {name, title, type} */ public function toArray() { return [ 'id' => $this->id, 'name' => $this->name, 'title' => $this->title, 'type' => $this->type, ]; } /** * Convert a value to the target type, validating it in the process * * @param mixed $value * @return bool|float|int|string */ public function cast($value) { switch ($this->type) { case 'int': if (is_int($value)) return $value; if (is_float($value)) return round($value); if (is_numeric($value)) return intval($value); throw new NotApplicableException("Could not convert value \"$value\" to int!"); case 'float': if (is_int($value) || is_float($value)) return (float)$value; if (is_numeric($value)) return floatval($value); throw new NotApplicableException("Could not convert value \"$value\" to float!"); case 'bool': return Utils::parseBool($value); case 'string': return "$value"; default: throw new \LogicException("Illegal column type: \"$this->type\""); } } /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php * @return mixed data which can be serialized by json_encode, * which is a value of any type other than a resource. * @since 5.4.0 */ public function jsonSerialize() { return $this->toArray(); } }