FromParam.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2018/10/18
  6. * Time: 上午9:28
  7. */
  8. namespace app\common\helpers\FormParam;
  9. use app\common\exceptions\AppException;
  10. use Illuminate\Database\Eloquent\Model;
  11. use app\framework\Database\Eloquent\Builder;
  12. /**
  13. * 表单参数助手
  14. * Class FromParam
  15. * @package app\common\helpers
  16. */
  17. class FromParam
  18. {
  19. private $params;
  20. private $format;
  21. private $isFormatted;
  22. public function __construct($params, $format = [])
  23. {
  24. $this->params = $params;
  25. $this->format = $format;
  26. }
  27. /**
  28. * @param $key
  29. * @return string
  30. * @throws AppException
  31. */
  32. private function getTypeClass($key)
  33. {
  34. if (isset($this->format[$key])) {
  35. $className = ucfirst($this->format[$key]);
  36. } else {
  37. $className = 'Equal';
  38. }
  39. $className = __NAMESPACE__ . '\\' . $className;
  40. if (!class_exists($className)) {
  41. throw new AppException('不存在的参数类型'.$className);
  42. }
  43. return $className;
  44. }
  45. /**
  46. * 根据参数生成where条件
  47. * todo 这个方法应该定义在哪个类中 $builder 怎么传递
  48. * @param Model $builder
  49. * @return Model
  50. * @throws AppException
  51. */
  52. public function toWhere($builder)
  53. {
  54. // 过滤调空的
  55. $result = array_filter($this->params, function ($value) {
  56. return isset($value) && $value !== '';
  57. });
  58. //根据key的类型
  59. foreach ($result as $key => $value) {
  60. $className = $this->getTypeClass($key);
  61. (new $className($builder))->format($key, $value);
  62. };
  63. return $builder;
  64. }
  65. // /**
  66. // * 输出所有参数
  67. // * @return mixed
  68. // */
  69. // public function toBuilder()
  70. // {
  71. // if (!$this->isFormatted) {
  72. // $this->params = $this->format($this->params);
  73. // }
  74. // return $this->params;
  75. // }
  76. }