PluginCallback.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\librarys;
  8. use Exception;
  9. use Yii;
  10. class PluginCallback
  11. {
  12. /**
  13. * 执行插件方法
  14. * @param bool $is_client
  15. * @return array|false|mixed
  16. */
  17. public static function execute($is_client = false, $is_alliance = false)
  18. {
  19. try {
  20. $callback = input_params('callback');
  21. if (! $callback) {
  22. throw new Exception('callback不存在');
  23. }
  24. $pluginSegment = explode('/', static::camelize($callback));
  25. if (count($pluginSegment) < 3) {
  26. throw new Exception('插件参数不够');
  27. }
  28. $pluginName = array_shift($pluginSegment);
  29. $actionName = sprintf('action%s', ucfirst(array_pop($pluginSegment)));
  30. $pluginPath = Yii::$app->basePath . '/plugins/' . $pluginName;
  31. if (! is_dir($pluginPath)) {
  32. throw new Exception('插件不存在: ' . $pluginName);
  33. }
  34. $pluginController = '';
  35. $lastKey = count($pluginSegment) - 1;
  36. foreach ($pluginSegment as $key => $item) {
  37. if ($key == $lastKey) {
  38. $pluginController .= ucfirst($item);
  39. } else {
  40. $pluginController .= $item . '\\';
  41. }
  42. }
  43. $str = 'app\plugins\%s\controllers\%sController';
  44. if ($is_client) {
  45. $str = 'app\plugins\%s\controllers\client\%sController';
  46. }
  47. if ($is_alliance) {
  48. $str = 'app\plugins\%s\controllers\alliance\%sController';
  49. }
  50. $pluginClass = sprintf($str, $pluginName, $pluginController);
  51. if (! class_exists($pluginClass)) {
  52. throw new Exception('插件类不存在: ' . $pluginClass);
  53. }
  54. if (! method_exists($pluginClass, $actionName)) {
  55. throw new Exception('插件方法不存在: ' . $actionName);
  56. }
  57. return call_user_func(array(new $pluginClass(Yii::$app->controller->id, Yii::$app->controller->module,
  58. ['callback' => $callback]), $actionName));
  59. } catch (\Throwable $throwable) {
  60. return [
  61. 'code' => 1,
  62. 'msg' => $throwable->getMessage(),
  63. 'line' => $throwable->getLine(),
  64. 'file' => $throwable->getFile()
  65. ];
  66. }
  67. }
  68. /**
  69. * @param $uncamelized_words
  70. * @param string $separator
  71. * @return string
  72. */
  73. private static function camelize($uncamelized_words, $separator = '-'): string
  74. {
  75. $uncamelized_words = $separator . str_replace($separator, ' ', strtolower($uncamelized_words));
  76. return ltrim(str_replace(' ', '', ucwords($uncamelized_words)), $separator);
  77. }
  78. }