<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think;
use ArrayAccess;
use Closure;
use JsonSerializable;
use think\contract\Arrayable;
use think\contract\Jsonable;
use think\db\BaseQuery as Query;
abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonable
{
use model\concern\Attribute;
use model\concern\RelationShip;
use model\concern\ModelEvent;
use model\concern\TimeStamp;
use model\concern\Conversion;
private $exists = false;
private $force = false;
private $replace = false;
protected $suffix;
private $updateWhere;
protected $connection;
protected $name;
protected $key;
protected $table;
protected static $initialized = [];
protected $defaultSoftDelete;
protected $globalScope = [];
private $lazySave = false;
protected static $db;
protected static $invoker;
protected static $maker = [];
protected static $macro = [];
public static function maker(Closure $maker)
{
static::$maker[] = $maker;
}
public static function macro(string $method, Closure $closure)
{
if (!isset(static::$macro[static::class])) {
static::$macro[static::class] = [];
}
static::$macro[static::class][$method] = $closure;
}
public static function setDb(DbManager $db)
{
self::$db = $db;
}
public static function setInvoker(callable $callable): void
{
self::$invoker = $callable;
}
public function invoke($method, array $vars = [])
{
if (self::$invoker) {
$call = self::$invoker;
return $call($method instanceof Closure ? $method : Closure::fromCallable([$this, $method]), $vars);
}
return call_user_func_array($method instanceof Closure ? $method : [$this, $method], $vars);
}
public function __construct(array $data = [])
{
$this->data = $data;
if (!empty($this->data)) {
foreach ((array) $this->disuse as $key) {
if (array_key_exists($key, $this->data)) {
unset($this->data[$key]);
}
}
}
$this->origin = $this->data;
if (empty($this->name)) {
$name = str_replace('\\', '/', static::class);
$this->name = basename($name);
}
if (!empty(static::$maker)) {
foreach (static::$maker as $maker) {
call_user_func($maker, $this);
}
}
$this->initialize();
}
public function getName(): string
{
return $this->name;
}
public function newInstance(array $data = [], $where = null): Model
{
$model = new static($data);
if ($this->connection) {
$model->setConnection($this->connection);
}
if ($this->suffix) {
$model->setSuffix($this->suffix);
}
if (empty($data)) {
return $model;
}
$model->exists(true);
$model->setUpdateWhere($where);
$model->trigger('AfterRead');
return $model;
}
protected function setUpdateWhere($where): void
{
$this->updateWhere = $where;
}
public function setConnection(string $connection)
{
$this->connection = $connection;
return $this;
}
public function getConnection(): string
{
return $this->connection ?: '';
}
public function setSuffix(string $suffix)
{
$this->suffix = $suffix;
return $this;
}
public function getSuffix(): string
{
return $this->suffix ?: '';
}
public function db($scope = []): Query
{
$query = self::$db->connect($this->connection)
->name($this->name . $this->suffix)
->pk($this->pk);
if (!empty($this->table)) {
$query->table($this->table . $this->suffix);
}
$query->model($this)
->json($this->json, $this->jsonAssoc)
->setFieldType(array_merge($this->schema, $this->jsonType));
if (property_exists($this, 'withTrashed') && !$this->withTrashed) {
$this->withNoTrashed($query);
}
if (is_array($scope)) {
$globalScope = array_diff($this->globalScope, $scope);
$query->scope($globalScope);
}
return $query;
}
private function initialize(): void
{
if (!isset(static::$initialized[static::class])) {
static::$initialized[static::class] = true;
static::init();
}
}
protected static function init()
{
}
protected function checkData(): void
{
}
protected function checkResult($result): void
{
}
public function force(bool $force = true)
{
$this->force = $force;
return $this;
}
public function isForce(): bool
{
return $this->force;
}
public function replace(bool $replace = true)
{
$this->replace = $replace;
return $this;
}
public function refresh(bool $relation = false)
{
if ($this->exists) {
$this->data = $this->db()->find($this->getKey())->getData();
$this->origin = $this->data;
$this->get = [];
if ($relation) {
$this->relation = [];
}
}
return $this;
}
public function exists(bool $exists = true)
{
$this->exists = $exists;
return $this;
}
public function isExists(): bool
{
return $this->exists;
}
public function isEmpty(): bool
{
return empty($this->data);
}
public function lazySave($data = []): void
{
if (false === $data) {
$this->lazySave = false;
} else {
if (is_array($data)) {
$this->setAttrs($data);
}
$this->lazySave = true;
}
}
public function save(array $data = [], string $sequence = null): bool
{
$this->setAttrs($data);
if ($this->isEmpty() || false === $this->trigger('BeforeWrite')) {
return false;
}
$result = $this->exists ? $this->updateData() : $this->insertData($sequence);
if (false === $result) {
return false;
}
$this->trigger('AfterWrite');
$this->origin = $this->data;
$this->get = [];
$this->lazySave = false;
return true;
}
protected function checkAllowFields(): array
{
if (empty($this->field)) {
if (!empty($this->schema)) {
$this->field = array_keys(array_merge($this->schema, $this->jsonType));
} else {
$query = $this->db();
$table = $this->table ? $this->table . $this->suffix : $query->getTable();
$this->field = $query->getConnection()->getTableFields($table);
}
return $this->field;
}
$field = $this->field;
if ($this->autoWriteTimestamp) {
array_push($field, $this->createTime, $this->updateTime);
}
if (!empty($this->disuse)) {
$field = array_diff($field, $this->disuse);
}
return $field;
}
protected function updateData(): bool
{
if (false === $this->trigger('BeforeUpdate')) {
return false;
}
$this->checkData();
$data = $this->getChangedData();
if (empty($data)) {
if (!empty($this->relationWrite)) {
$this->autoRelationUpdate();
}
return true;
}
if ($this->autoWriteTimestamp && $this->updateTime) {
$data[$this->updateTime] = $this->autoWriteTimestamp();
$this->data[$this->updateTime] = $this->getTimestampValue($data[$this->updateTime]);
}
$allowFields = $this->checkAllowFields();
foreach ($this->relationWrite as $name => $val) {
if (!is_array($val)) {
continue;
}
foreach ($val as $key) {
if (isset($data[$key])) {
unset($data[$key]);
}
}
}
$db = $this->db();
$db->transaction(function () use ($data, $allowFields, $db) {
$this->key = null;
$where = $this->getWhere();
$result = $db->where($where)
->strict(false)
->cache(true)
->setOption('key', $this->key)
->field($allowFields)
->update($data);
$this->checkResult($result);
if (!empty($this->relationWrite)) {
$this->autoRelationUpdate();
}
});
$this->trigger('AfterUpdate');
return true;
}
protected function insertData(string $sequence = null): bool
{
if (false === $this->trigger('BeforeInsert')) {
return false;
}
$this->checkData();
$data = $this->data;
if ($this->autoWriteTimestamp) {
if ($this->createTime && !isset($data[$this->createTime])) {
$data[$this->createTime] = $this->autoWriteTimestamp();
$this->data[$this->createTime] = $this->getTimestampValue($data[$this->createTime]);
}
if ($this->updateTime && !isset($data[$this->updateTime])) {
$data[$this->updateTime] = $this->autoWriteTimestamp();
$this->data[$this->updateTime] = $this->getTimestampValue($data[$this->updateTime]);
}
}
$allowFields = $this->checkAllowFields();
$db = $this->db();
$db->transaction(function () use ($data, $sequence, $allowFields, $db) {
$result = $db->strict(false)
->field($allowFields)
->replace($this->replace)
->sequence($sequence)
->insert($data, true);
if ($result) {
$pk = $this->getPk();
if (is_string($pk) && (!isset($this->data[$pk]) || '' == $this->data[$pk])) {
unset($this->get[$pk]);
$this->data[$pk] = $result;
}
}
if (!empty($this->relationWrite)) {
$this->autoRelationInsert();
}
});
$this->exists = true;
$this->origin = $this->data;
$this->trigger('AfterInsert');
return true;
}
public function getWhere()
{
$pk = $this->getPk();
if (is_string($pk) && isset($this->origin[$pk])) {
$where = [[$pk, '=', $this->origin[$pk]]];
$this->key = $this->origin[$pk];
} elseif (is_array($pk)) {
foreach ($pk as $field) {
if (isset($this->origin[$field])) {
$where[] = [$field, '=', $this->origin[$field]];
}
}
}
if (empty($where)) {
$where = empty($this->updateWhere) ? null : $this->updateWhere;
}
return $where;
}
public function saveAll(iterable $dataSet, bool $replace = true): Collection
{
$db = $this->db();
$result = $db->transaction(function () use ($replace, $dataSet) {
$pk = $this->getPk();
if (is_string($pk) && $replace) {
$auto = true;
}
$result = [];
$suffix = $this->getSuffix();
foreach ($dataSet as $key => $data) {
if ($this->exists || (!empty($auto) && isset($data[$pk]))) {
$result[$key] = static::update($data, [], [], $suffix);
} else {
$result[$key] = static::create($data, $this->field, $this->replace, $suffix);
}
}
return $result;
});
return $this->toCollection($result);
}
public function delete(): bool
{
if (!$this->exists || $this->isEmpty() || false === $this->trigger('BeforeDelete')) {
return false;
}
$where = $this->getWhere();
$db = $this->db();
$db->transaction(function () use ($where, $db) {
$db->where($where)->delete();
if (!empty($this->relationWrite)) {
$this->autoRelationDelete();
}
});
$this->trigger('AfterDelete');
$this->exists = false;
$this->lazySave = false;
return true;
}
public static function create(array $data, array $allowField = [], bool $replace = false, string $suffix = ''): Model
{
$model = new static();
if (!empty($allowField)) {
$model->allowField($allowField);
}
if (!empty($suffix)) {
$model->setSuffix($suffix);
}
$model->replace($replace)->save($data);
return $model;
}
public static function update(array $data, $where = [], array $allowField = [], string $suffix = '')
{
$model = new static();
if (!empty($allowField)) {
$model->allowField($allowField);
}
if (!empty($where)) {
$model->setUpdateWhere($where);
}
if (!empty($suffix)) {
$model->setSuffix($suffix);
}
$model->exists(true)->save($data);
return $model;
}
public static function destroy($data, bool $force = false): bool
{
if (empty($data) && 0 !== $data) {
return false;
}
$model = new static();
$query = $model->db();
if (is_array($data) && key($data) !== 0) {
$query->where($data);
$data = null;
} elseif ($data instanceof \Closure) {
$data($query);
$data = null;
}
$resultSet = $query->select($data);
foreach ($resultSet as $result) {
$result->force($force)->delete();
}
return true;
}
public function __wakeup()
{
$this->initialize();
}
public function __set(string $name, $value): void
{
$this->setAttr($name, $value);
}
public function __get(string $name)
{
return $this->getAttr($name);
}
public function __isset(string $name): bool
{
return !is_null($this->getAttr($name));
}
public function __unset(string $name): void
{
unset($this->data[$name],
$this->get[$name],
$this->relation[$name]);
}
public function offsetSet($name, $value)
{
$this->setAttr($name, $value);
}
public function offsetExists($name): bool
{
return $this->__isset($name);
}
public function offsetUnset($name)
{
$this->__unset($name);
}
public function offsetGet($name)
{
return $this->getAttr($name);
}
public static function withoutGlobalScope(array $scope = null)
{
$model = new static();
return $model->db($scope);
}
public static function suffix(string $suffix)
{
$model = new static();
$model->setSuffix($suffix);
return $model;
}
public static function connect(string $connection)
{
$model = new static();
$model->setConnection($connection);
return $model;
}
public function __call($method, $args)
{
if (isset(static::$macro[static::class][$method])) {
return call_user_func_array(static::$macro[static::class][$method]->bindTo($this, static::class), $args);
}
if ('withattr' == strtolower($method)) {
return call_user_func_array([$this, 'withAttribute'], $args);
}
return call_user_func_array([$this->db(), $method], $args);
}
public static function __callStatic($method, $args)
{
if (isset(static::$macro[static::class][$method])) {
return call_user_func_array(static::$macro[static::class][$method]->bindTo(null, static::class), $args);
}
$model = new static();
return call_user_func_array([$model->db(), $method], $args);
}
public function __destruct()
{
if ($this->lazySave) {
$this->save();
}
}
}