RuleService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace addons\Wechat\services;
  3. use Yii;
  4. use yii\helpers\Json;
  5. use common\components\Service;
  6. use common\helpers\ExecuteHelper;
  7. /**
  8. * Class RuleService
  9. * @package addons\Wechat\services
  10. * @author jianyan74 <751393839@qq.com>
  11. */
  12. class RuleService extends Service
  13. {
  14. /**
  15. * 返回自定义接口信息
  16. *
  17. * @param $model
  18. * @param $wechatMessage
  19. * @return mixed
  20. * @throws \yii\web\NotFoundHttpException
  21. */
  22. public function getApiData($model, $wechatMessage)
  23. {
  24. $modelData = Json::decode($model->data);
  25. $class = Yii::$app->params['userApiNamespace'] . '\\' . $modelData['api_url'];
  26. // 读取接口信息
  27. if ($modelData['cache_time'] > 0) {
  28. $content = isset($wechatMessage['Content']) ? $wechatMessage['Content'] : '';
  29. // 尝试从缓存中取回 $data
  30. $key = Yii::$app->params['userApiCachePrefixKey'] . $modelData['api_url'] . $content;
  31. if (!($data = Yii::$app->cache->get($key))) {
  32. $data = ExecuteHelper::map($class, 'run', $wechatMessage);
  33. Yii::$app->cache->set($key, $data, $modelData['cache_time']);
  34. }
  35. return $data;
  36. }
  37. return ExecuteHelper::map($class, 'run', $wechatMessage);
  38. }
  39. /**
  40. * 获取本地的api文件列表
  41. *
  42. * @return array
  43. */
  44. public function getApiList()
  45. {
  46. $api_dir = Yii::$app->params['userApiPath'];
  47. // 获取api列表
  48. $dirs = array_map('basename', glob($api_dir . '/*'));
  49. $list = [];
  50. foreach ($dirs as $dir) {
  51. // 正则匹配文件名
  52. if (preg_match('/Api.(php)$/', $dir)) {
  53. $list[] = $dir;
  54. }
  55. }
  56. $arr = [];
  57. foreach ($list as $value) {
  58. $key = str_replace(".php", "", $value);
  59. $arr[$key] = $value;
  60. }
  61. return $arr;
  62. }
  63. }
粤ICP备19079148号