Attribute.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think\model\concern;
  13. use InvalidArgumentException;
  14. use think\db\Raw;
  15. use think\helper\Str;
  16. use think\model\Relation;
  17. /**
  18. * 模型数据处理
  19. */
  20. trait Attribute
  21. {
  22. /**
  23. * 数据表主键 复合主键使用数组定义
  24. * @var string|array
  25. */
  26. protected $pk = 'id';
  27. /**
  28. * 数据表字段信息 留空则自动获取
  29. * @var array
  30. */
  31. protected $schema = [];
  32. /**
  33. * 当前允许写入的字段
  34. * @var array
  35. */
  36. protected $field = [];
  37. /**
  38. * 字段自动类型转换
  39. * @var array
  40. */
  41. protected $type = [];
  42. /**
  43. * 数据表废弃字段
  44. * @var array
  45. */
  46. protected $disuse = [];
  47. /**
  48. * 数据表只读字段
  49. * @var array
  50. */
  51. protected $readonly = [];
  52. /**
  53. * 当前模型数据
  54. * @var array
  55. */
  56. private $data = [];
  57. /**
  58. * 原始数据
  59. * @var array
  60. */
  61. private $origin = [];
  62. /**
  63. * JSON数据表字段
  64. * @var array
  65. */
  66. protected $json = [];
  67. /**
  68. * JSON数据表字段类型
  69. * @var array
  70. */
  71. protected $jsonType = [];
  72. /**
  73. * JSON数据取出是否需要转换为数组
  74. * @var bool
  75. */
  76. protected $jsonAssoc = false;
  77. /**
  78. * 是否严格字段大小写
  79. * @var bool
  80. */
  81. protected $strict = true;
  82. /**
  83. * 修改器执行记录
  84. * @var array
  85. */
  86. private $set = [];
  87. /**
  88. * 动态获取器
  89. * @var array
  90. */
  91. private $withAttr = [];
  92. /**
  93. * 获取模型对象的主键
  94. * @access public
  95. * @return string|array
  96. */
  97. public function getPk()
  98. {
  99. return $this->pk;
  100. }
  101. /**
  102. * 判断一个字段名是否为主键字段
  103. * @access public
  104. * @param string $key 名称
  105. * @return bool
  106. */
  107. protected function isPk(string $key): bool
  108. {
  109. $pk = $this->getPk();
  110. if (is_string($pk) && $pk == $key) {
  111. return true;
  112. } elseif (is_array($pk) && in_array($key, $pk)) {
  113. return true;
  114. }
  115. return false;
  116. }
  117. /**
  118. * 获取模型对象的主键值
  119. * @access public
  120. * @return mixed
  121. */
  122. public function getKey()
  123. {
  124. $pk = $this->getPk();
  125. if (is_string($pk) && array_key_exists($pk, $this->data)) {
  126. return $this->data[$pk];
  127. }
  128. return;
  129. }
  130. /**
  131. * 设置允许写入的字段
  132. * @access public
  133. * @param array $field 允许写入的字段
  134. * @return $this
  135. */
  136. public function allowField(array $field)
  137. {
  138. $this->field = $field;
  139. return $this;
  140. }
  141. /**
  142. * 设置只读字段
  143. * @access public
  144. * @param array $field 只读字段
  145. * @return $this
  146. */
  147. public function readOnly(array $field)
  148. {
  149. $this->readonly = $field;
  150. return $this;
  151. }
  152. /**
  153. * 获取实际的字段名
  154. * @access protected
  155. * @param string $name 字段名
  156. * @return string
  157. */
  158. protected function getRealFieldName(string $name): string
  159. {
  160. return $this->strict ? $name : Str::snake($name);
  161. }
  162. /**
  163. * 设置数据对象值
  164. * @access public
  165. * @param array $data 数据
  166. * @param bool $set 是否调用修改器
  167. * @param array $allow 允许的字段名
  168. * @return $this
  169. */
  170. public function data(array $data, bool $set = false, array $allow = [])
  171. {
  172. // 清空数据
  173. $this->data = [];
  174. // 废弃字段
  175. foreach ($this->disuse as $key) {
  176. if (array_key_exists($key, $data)) {
  177. unset($data[$key]);
  178. }
  179. }
  180. if (!empty($allow)) {
  181. $result = [];
  182. foreach ($allow as $name) {
  183. if (isset($data[$name])) {
  184. $result[$name] = $data[$name];
  185. }
  186. }
  187. $data = $result;
  188. }
  189. if ($set) {
  190. // 数据对象赋值
  191. $this->setAttrs($data);
  192. } else {
  193. $this->data = $data;
  194. }
  195. return $this;
  196. }
  197. /**
  198. * 批量追加数据对象值
  199. * @access public
  200. * @param array $data 数据
  201. * @param bool $set 是否需要进行数据处理
  202. * @return $this
  203. */
  204. public function appendData(array $data, bool $set = false)
  205. {
  206. if ($set) {
  207. $this->setAttrs($data);
  208. } else {
  209. $this->data = array_merge($this->data, $data);
  210. }
  211. return $this;
  212. }
  213. /**
  214. * 获取对象原始数据 如果不存在指定字段返回null
  215. * @access public
  216. * @param string $name 字段名 留空获取全部
  217. * @return mixed
  218. */
  219. public function getOrigin(string $name = null)
  220. {
  221. if (is_null($name)) {
  222. return $this->origin;
  223. }
  224. return array_key_exists($name, $this->origin) ? $this->origin[$name] : null;
  225. }
  226. /**
  227. * 获取对象原始数据 如果不存在指定字段返回false
  228. * @access public
  229. * @param string $name 字段名 留空获取全部
  230. * @return mixed
  231. * @throws InvalidArgumentException
  232. */
  233. public function getData(string $name = null)
  234. {
  235. if (is_null($name)) {
  236. return $this->data;
  237. }
  238. $fieldName = $this->getRealFieldName($name);
  239. if (array_key_exists($fieldName, $this->data)) {
  240. return $this->data[$fieldName];
  241. } elseif (array_key_exists($fieldName, $this->relation)) {
  242. return $this->relation[$fieldName];
  243. }
  244. throw new InvalidArgumentException('property not exists:' . static::class . '->' . $name);
  245. }
  246. /**
  247. * 获取变化的数据 并排除只读数据
  248. * @access public
  249. * @return array
  250. */
  251. public function getChangedData(): array
  252. {
  253. $data = $this->force ? $this->data : array_udiff_assoc($this->data, $this->origin, function ($a, $b) {
  254. if ((empty($a) || empty($b)) && $a !== $b) {
  255. return 1;
  256. }
  257. return is_object($a) || $a != $b ? 1 : 0;
  258. });
  259. // 只读字段不允许更新
  260. foreach ($this->readonly as $key => $field) {
  261. if (isset($data[$field])) {
  262. unset($data[$field]);
  263. }
  264. }
  265. return $data;
  266. }
  267. /**
  268. * 直接设置数据对象值
  269. * @access public
  270. * @param string $name 属性名
  271. * @param mixed $value 值
  272. * @return void
  273. */
  274. public function set(string $name, $value): void
  275. {
  276. $name = $this->getRealFieldName($name);
  277. $this->data[$name] = $value;
  278. }
  279. /**
  280. * 通过修改器 批量设置数据对象值
  281. * @access public
  282. * @param array $data 数据
  283. * @return void
  284. */
  285. public function setAttrs(array $data): void
  286. {
  287. // 进行数据处理
  288. foreach ($data as $key => $value) {
  289. $this->setAttr($key, $value, $data);
  290. }
  291. }
  292. /**
  293. * 通过修改器 设置数据对象值
  294. * @access public
  295. * @param string $name 属性名
  296. * @param mixed $value 属性值
  297. * @param array $data 数据
  298. * @return void
  299. */
  300. public function setAttr(string $name, $value, array $data = []): void
  301. {
  302. $name = $this->getRealFieldName($name);
  303. if (isset($this->set[$name])) {
  304. return;
  305. }
  306. if (is_null($value) && $this->autoWriteTimestamp && in_array($name, [$this->createTime, $this->updateTime])) {
  307. // 自动写入的时间戳字段
  308. $value = $this->autoWriteTimestamp();
  309. } else {
  310. // 检测修改器
  311. $method = 'set' . Str::studly($name) . 'Attr';
  312. if (method_exists($this, $method)) {
  313. $array = $this->data;
  314. $value = $this->$method($value, array_merge($this->data, $data));
  315. $this->set[$name] = true;
  316. if (is_null($value) && $array !== $this->data) {
  317. return;
  318. }
  319. } elseif (isset($this->type[$name])) {
  320. // 类型转换
  321. $value = $this->writeTransform($value, $this->type[$name]);
  322. }
  323. }
  324. // 设置数据对象属性
  325. $this->data[$name] = $value;
  326. }
  327. /**
  328. * 数据写入 类型转换
  329. * @access protected
  330. * @param mixed $value 值
  331. * @param string|array $type 要转换的类型
  332. * @return mixed
  333. */
  334. protected function writeTransform($value, $type)
  335. {
  336. if (is_null($value)) {
  337. return;
  338. }
  339. if ($value instanceof Raw) {
  340. return $value;
  341. }
  342. if (is_array($type)) {
  343. list($type, $param) = $type;
  344. } elseif (strpos($type, ':')) {
  345. list($type, $param) = explode(':', $type, 2);
  346. }
  347. switch ($type) {
  348. case 'integer':
  349. $value = (int) $value;
  350. break;
  351. case 'float':
  352. if (empty($param)) {
  353. $value = (float) $value;
  354. } else {
  355. $value = (float) number_format($value, $param, '.', '');
  356. }
  357. break;
  358. case 'boolean':
  359. $value = (bool) $value;
  360. break;
  361. case 'timestamp':
  362. if (!is_numeric($value)) {
  363. $value = strtotime($value);
  364. }
  365. break;
  366. case 'datetime':
  367. $value = is_numeric($value) ? $value : strtotime($value);
  368. $value = $this->formatDateTime('Y-m-d H:i:s.u', $value);
  369. break;
  370. case 'object':
  371. if (is_object($value)) {
  372. $value = json_encode($value, JSON_FORCE_OBJECT);
  373. }
  374. break;
  375. case 'array':
  376. $value = (array) $value;
  377. case 'json':
  378. $option = !empty($param) ? (int) $param : JSON_UNESCAPED_UNICODE;
  379. $value = json_encode($value, $option);
  380. break;
  381. case 'serialize':
  382. $value = serialize($value);
  383. break;
  384. default:
  385. if (is_object($value) && false !== strpos($type, '\\') && method_exists($value, '__toString')) {
  386. // 对象类型
  387. $value = $value->__toString();
  388. }
  389. }
  390. return $value;
  391. }
  392. /**
  393. * 获取器 获取数据对象的值
  394. * @access public
  395. * @param string $name 名称
  396. * @return mixed
  397. * @throws InvalidArgumentException
  398. */
  399. public function getAttr(string $name)
  400. {
  401. try {
  402. $relation = false;
  403. $value = $this->getData($name);
  404. } catch (InvalidArgumentException $e) {
  405. $relation = $this->isRelationAttr($name);
  406. $value = null;
  407. }
  408. return $this->getValue($name, $value, $relation);
  409. }
  410. /**
  411. * 获取经过获取器处理后的数据对象的值
  412. * @access protected
  413. * @param string $name 字段名称
  414. * @param mixed $value 字段值
  415. * @param bool|string $relation 是否为关联属性或者关联名
  416. * @return mixed
  417. * @throws InvalidArgumentException
  418. */
  419. protected function getValue(string $name, $value, $relation = false)
  420. {
  421. // 检测属性获取器
  422. $fieldName = $this->getRealFieldName($name);
  423. $method = 'get' . Str::studly($name) . 'Attr';
  424. if (isset($this->withAttr[$fieldName])) {
  425. if ($relation) {
  426. $value = $this->getRelationValue($relation);
  427. }
  428. if (in_array($fieldName, $this->json) && is_array($this->withAttr[$fieldName])) {
  429. $value = $this->getJsonValue($fieldName, $value);
  430. } else {
  431. $closure = $this->withAttr[$fieldName];
  432. $value = $closure($value, $this->data);
  433. }
  434. } elseif (method_exists($this, $method)) {
  435. if ($relation) {
  436. $value = $this->getRelationValue($relation);
  437. }
  438. $value = $this->$method($value, $this->data);
  439. } elseif (isset($this->type[$fieldName])) {
  440. // 类型转换
  441. $value = $this->readTransform($value, $this->type[$fieldName]);
  442. } elseif ($this->autoWriteTimestamp && in_array($fieldName, [$this->createTime, $this->updateTime])) {
  443. $value = $this->getTimestampValue($value);
  444. } elseif ($relation) {
  445. $value = $this->getRelationValue($relation);
  446. // 保存关联对象值
  447. $this->relation[$name] = $value;
  448. }
  449. return $value;
  450. }
  451. /**
  452. * 获取JSON字段属性值
  453. * @access protected
  454. * @param string $name 属性名
  455. * @param mixed $value JSON数据
  456. * @return mixed
  457. */
  458. protected function getJsonValue($name, $value)
  459. {
  460. foreach ($this->withAttr[$name] as $key => $closure) {
  461. if ($this->jsonAssoc) {
  462. $value[$key] = $closure($value[$key], $value);
  463. } else {
  464. $value->$key = $closure($value->$key, $value);
  465. }
  466. }
  467. return $value;
  468. }
  469. /**
  470. * 获取关联属性值
  471. * @access protected
  472. * @param string $relation 关联名
  473. * @return mixed
  474. */
  475. protected function getRelationValue(string $relation)
  476. {
  477. $modelRelation = $this->$relation();
  478. return $modelRelation instanceof Relation ? $this->getRelationData($modelRelation) : null;
  479. }
  480. /**
  481. * 数据读取 类型转换
  482. * @access protected
  483. * @param mixed $value 值
  484. * @param string|array $type 要转换的类型
  485. * @return mixed
  486. */
  487. protected function readTransform($value, $type)
  488. {
  489. if (is_null($value)) {
  490. return;
  491. }
  492. if (is_array($type)) {
  493. list($type, $param) = $type;
  494. } elseif (strpos($type, ':')) {
  495. list($type, $param) = explode(':', $type, 2);
  496. }
  497. switch ($type) {
  498. case 'integer':
  499. $value = (int) $value;
  500. break;
  501. case 'float':
  502. if (empty($param)) {
  503. $value = (float) $value;
  504. } else {
  505. $value = (float) number_format($value, $param, '.', '');
  506. }
  507. break;
  508. case 'boolean':
  509. $value = (bool) $value;
  510. break;
  511. case 'timestamp':
  512. if (!is_null($value)) {
  513. $format = !empty($param) ? $param : $this->dateFormat;
  514. $value = $this->formatDateTime($format, $value, true);
  515. }
  516. break;
  517. case 'datetime':
  518. if (!is_null($value)) {
  519. $format = !empty($param) ? $param : $this->dateFormat;
  520. $value = $this->formatDateTime($format, $value);
  521. }
  522. break;
  523. case 'json':
  524. $value = json_decode($value, true);
  525. break;
  526. case 'array':
  527. $value = empty($value) ? [] : json_decode($value, true);
  528. break;
  529. case 'object':
  530. $value = empty($value) ? new \stdClass() : json_decode($value);
  531. break;
  532. case 'serialize':
  533. try {
  534. $value = unserialize($value);
  535. } catch (\Exception $e) {
  536. $value = null;
  537. }
  538. break;
  539. default:
  540. if (false !== strpos($type, '\\')) {
  541. // 对象类型
  542. $value = new $type($value);
  543. }
  544. }
  545. return $value;
  546. }
  547. /**
  548. * 设置数据字段获取器
  549. * @access public
  550. * @param string|array $name 字段名
  551. * @param callable $callback 闭包获取器
  552. * @return $this
  553. */
  554. public function withAttribute($name, callable $callback = null)
  555. {
  556. if (is_array($name)) {
  557. foreach ($name as $key => $val) {
  558. $this->withAttribute($key, $val);
  559. }
  560. } else {
  561. $name = $this->getRealFieldName($name);
  562. if (strpos($name, '.')) {
  563. list($name, $key) = explode('.', $name);
  564. $this->withAttr[$name][$key] = $callback;
  565. } else {
  566. $this->withAttr[$name] = $callback;
  567. }
  568. }
  569. return $this;
  570. }
  571. }