Files
kiri-databases/Traits/HasBase.php
T

106 lines
2.3 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/4 0004
* Time: 15:47
*/
declare(strict_types=1);
namespace Database\Traits;
use Database\ModelInterface;
use Database\Collection;
use Database\Relation;
use Exception;
/**
* Class HasBase
* @package Database
*
* @include Query
*/
abstract class HasBase implements \Database\Traits\Relation
{
2022-09-29 22:51:41 +08:00
2022-01-09 03:49:51 +08:00
/** @var ModelInterface|Collection */
protected Collection|ModelInterface $data;
2022-09-29 22:51:41 +08:00
2022-01-09 03:49:51 +08:00
/**
* @var ModelInterface
*/
protected mixed $model;
2022-09-29 22:51:41 +08:00
protected mixed $value = 0;
2022-01-09 03:49:51 +08:00
/** @var Relation $_relation */
protected Relation $_relation;
2022-09-29 22:51:41 +08:00
2022-09-29 18:54:14 +08:00
/**
* HasBase constructor.
* @param ModelInterface $model
2022-09-29 18:58:32 +08:00
* @param string $primaryId
2022-09-29 18:54:14 +08:00
* @param $value
* @param Relation $relation
* @throws Exception
*/
2022-09-29 18:58:32 +08:00
public function __construct(mixed $model, public string $primaryId, $value, Relation $relation)
2022-01-09 03:49:51 +08:00
{
if (!class_exists($model)) {
throw new Exception('Model must implement ' . $model);
}
if (!in_array(ModelInterface::class, class_implements($model))) {
throw new Exception('Model must implement ' . $model);
}
if (is_array($value)) {
if (empty($value)) $value = [];
$_model = $model::query()->whereIn($primaryId, $value);
} else {
$_model = $model::query()->where(['t1.' . $primaryId => $value]);
}
2022-09-29 22:51:41 +08:00
$this->value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
$this->_relation = $relation->bindIdentification(md5($model . '_' . $primaryId . '_' . $this->value), $_model);
2022-01-09 03:49:51 +08:00
$this->model = $model;
}
2022-09-29 22:51:41 +08:00
/**
* @param $name
* @param $arguments
* @return static
*/
public function __call($name, $arguments)
{
if (!method_exists($this, $name)) {
2022-09-29 22:53:39 +08:00
$key = $this->model . '_' . $this->primaryId . '_' . $this->value;
2022-09-29 23:06:07 +08:00
$this->_relation->getQuery($this->reKey())->$name(...$arguments);
2022-09-29 22:51:41 +08:00
} else {
call_user_func([$this, $name], ...$arguments);
}
return $this;
}
2022-09-29 23:06:07 +08:00
/**
* @return string
*/
protected function reKey(): string
{
return md5($this->model . '_' . $this->primaryId . '_' . $this->value);
}
2022-01-09 03:49:51 +08:00
/**
* @param $name
* @return mixed
*/
public function __get($name): mixed
{
if (empty($this->value)) {
return null;
}
return $this->get();
}
}