ConfigValueRepository.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\common\repositories\system\config;
  3. use app\common\dao\system\config\SystemConfigValueDao;
  4. use app\common\repositories\BaseRepository;
  5. use think\exception\ValidateException;
  6. use think\facade\Db;
  7. /**
  8. * Class ConfigValueRepository
  9. * @package app\common\repositories\system\config
  10. * @mixin SystemConfigValueDao
  11. */
  12. class ConfigValueRepository extends BaseRepository
  13. {
  14. /**
  15. * ConfigValueRepository constructor.
  16. * @param SystemConfigValueDao $dao
  17. */
  18. public function __construct(SystemConfigValueDao $dao)
  19. {
  20. $this->dao = $dao;
  21. }
  22. /**
  23. * @param array $keys
  24. * @param int $merId
  25. * @return array
  26. * @author zfy
  27. * @day 2020-03-27
  28. */
  29. public function more(array $keys, int $merId): array
  30. {
  31. $config = $this->dao->fields($keys, $merId);
  32. foreach ($keys as $key) {
  33. if (!isset($config[$key])) $config[$key] = '';
  34. }
  35. return $config;
  36. }
  37. /**
  38. * @param string $key
  39. * @param int $merId
  40. * @return mixed|string|null
  41. * @author zfy
  42. * @day 2020-05-08
  43. */
  44. public function get(string $key, int $merId)
  45. {
  46. $value = $this->dao->value($key, $merId);
  47. return $value ?? '';
  48. }
  49. /**
  50. * @param int $cid
  51. * @param array $formData
  52. * @param int $merId
  53. * @author zfy
  54. * @day 2020-03-27
  55. */
  56. public function save(int $cid, array $formData, int $merId)
  57. {
  58. $keys = array_keys($formData);
  59. $keys = app()->make(ConfigRepository::class)->intersectionKey($cid, $keys);
  60. if (!count($keys)) return;
  61. foreach ($keys as $key => $info) {
  62. if (!isset($formData[$key]))
  63. unset($formData[$key]);
  64. else {
  65. if ($info['config_type'] == 'number') {
  66. if ($formData[$key] === '' || $formData[$key] < 0)
  67. throw new ValidateException($info['config_name'] . '不能小于0');
  68. $formData[$key] = floatval($formData[$key]);
  69. }
  70. }
  71. }
  72. $this->setFormData($formData, $merId);
  73. }
  74. public function setFormData(array $formData, int $merId)
  75. {
  76. Db::transaction(function () use ($merId, $formData) {
  77. foreach ($formData as $key => $value) {
  78. if ($this->dao->merExists($key, $merId))
  79. $this->dao->merUpdate($merId, $key, ['value' => $value]);
  80. else
  81. $this->dao->create([
  82. 'mer_id' => $merId,
  83. 'value' => $value,
  84. 'config_key' => $key
  85. ]);
  86. }
  87. });
  88. }
  89. }