diff --git a/src/Auth/Model.php b/src/Auth/Model.php new file mode 100644 index 0000000..03932ab --- /dev/null +++ b/src/Auth/Model.php @@ -0,0 +1,120 @@ +db = $data['db']; + $this->user = $data['user']; + $this->table = $data['table']; + } + + /** + * Create a new model resource + * + * @param array $data Data to be inserted + * + * @return bool + */ + public function create(array $data): bool + { + $data['user_id'] = $this->user->id(); + + if (Config::get('timestamps')) { + $now = (new \Leaf\Date())->tick()->format(Config::get('timestamps.format')); + $data['created_at'] = $now; + $data['updated_at'] = $now; + } + + return $this->db->table($this->table)->insert($data)->execute(); + } + + /** + * Update a model resource + * + * @param array $data Data to be updated + * + * @return \Leaf\Db + */ + public function update(array $data): \Leaf\Db + { + $data['updated_at'] = (new \Leaf\Date())->tick()->format(Config::get('timestamps.format')); + + return $this->db->update($this->table) + ->params($data) + ->where('user_id', $this->user->id()); + } + + /** + * Delete a model resource + * + * @return \Leaf\Db + */ + public function delete(): \Leaf\Db + { + return $this->db->delete($this->table) + ->where('user_id', $this->user->id()); + } + + /** + * Get a model resource + * + * @param string $columns Columns to search by separated by commas or * + * + * @return \Leaf\Db + */ + public function get($columns = '*'): \Leaf\Db + { + return $this->db->select($this->table, $columns) + ->where('user_id', $this->user->id()); + } + + /** + * Save a model resource + * + * @return bool + */ + public function save(): bool + { + $success = $this->create($this->dataToSave); + + $this->dataToSave = []; + + return $success; + } + + public function __set($name, $value) + { + $this->dataToSave[$name] = $value; + } +} diff --git a/src/Auth/User.php b/src/Auth/User.php index 45ab149..1f8258b 100644 --- a/src/Auth/User.php +++ b/src/Auth/User.php @@ -212,7 +212,8 @@ public function __unset($name) * @param mixed $method The table to relate to * @param mixed $args * @throws \Exception - * @return Db + * + * @return Model */ public function __call($method, $args) { @@ -220,9 +221,10 @@ public function __call($method, $args) throw new \Exception('Relations are only available in Leaf apps.'); } - return auth() - ->db() - ->select($method) - ->where('user_id', $this->id()); + return (new Model([ + 'user' => $this, + 'table' => $method, + 'db' => auth()->db(), + ])); } }