| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\librarys;
- use Exception;
- use Yii;
- class PluginCallback
- {
- /**
- * 执行插件方法
- * @param bool $is_client
- * @return array|false|mixed
- */
- public static function execute($is_client = false, $is_alliance = false)
- {
- try {
- $callback = input_params('callback');
- if (! $callback) {
- throw new Exception('callback不存在');
- }
- $pluginSegment = explode('/', static::camelize($callback));
- if (count($pluginSegment) < 3) {
- throw new Exception('插件参数不够');
- }
- $pluginName = array_shift($pluginSegment);
- $actionName = sprintf('action%s', ucfirst(array_pop($pluginSegment)));
- $pluginPath = Yii::$app->basePath . '/plugins/' . $pluginName;
- if (! is_dir($pluginPath)) {
- throw new Exception('插件不存在: ' . $pluginName);
- }
- $pluginController = '';
- $lastKey = count($pluginSegment) - 1;
- foreach ($pluginSegment as $key => $item) {
- if ($key == $lastKey) {
- $pluginController .= ucfirst($item);
- } else {
- $pluginController .= $item . '\\';
- }
- }
- $str = 'app\plugins\%s\controllers\%sController';
- if ($is_client) {
- $str = 'app\plugins\%s\controllers\client\%sController';
- }
- if ($is_alliance) {
- $str = 'app\plugins\%s\controllers\alliance\%sController';
- }
- $pluginClass = sprintf($str, $pluginName, $pluginController);
- if (! class_exists($pluginClass)) {
- throw new Exception('插件类不存在: ' . $pluginClass);
- }
- if (! method_exists($pluginClass, $actionName)) {
- throw new Exception('插件方法不存在: ' . $actionName);
- }
- return call_user_func(array(new $pluginClass(Yii::$app->controller->id, Yii::$app->controller->module,
- ['callback' => $callback]), $actionName));
- } catch (\Throwable $throwable) {
- return [
- 'code' => 1,
- 'msg' => $throwable->getMessage(),
- 'line' => $throwable->getLine(),
- 'file' => $throwable->getFile()
- ];
- }
- }
- /**
- * @param $uncamelized_words
- * @param string $separator
- * @return string
- */
- private static function camelize($uncamelized_words, $separator = '-'): string
- {
- $uncamelized_words = $separator . str_replace($separator, ' ', strtolower($uncamelized_words));
- return ltrim(str_replace(' ', '', ucwords($uncamelized_words)), $separator);
- }
- }
|