• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

miaoxing / plugin / 6056293912

02 Sep 2023 04:05AM UTC coverage: 39.232% (-0.05%) from 39.283%
6056293912

push

github

twinh
feat(Ret, experimental): 增加 `assert` 方法,当 ret 为错误时,抛出异常

0 of 3 new or added lines in 1 file covered. (0.0%)

920 of 2345 relevant lines covered (39.23%)

18.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.59
/src/Service/Ret.php
1
<?php
2

3
namespace Miaoxing\Plugin\Service;
4

5
use Wei\BaseModel;
6
use Wei\Req;
7
use Wei\Res;
8
use Wei\Ret\RetException;
9

10
/**
11
 * @OA\Schema(
12
 *   schema="Ret",
13
 *   required={"code", "message"}
14
 * )
15
 * @OA\Property(
16
 *   property="code",
17
 *   type="integer",
18
 *   description="返回编号"
19
 * )
20
 * @OA\Property(
21
 *   property="message",
22
 *   type="string",
23
 *   description="返回信息"
24
 * )
25
 * @mixin \PluginMixin
26
 * @mixin \EnvMixin
27
 * @mixin \ReqMixin
28
 * @mixin \ResMixin
29
 * @mixin \ViewMixin
30
 */
31
class Ret extends \Wei\Ret
32
{
33
    /**
34
     * @var array
35
     * @internal
36
     */
37
    protected static $errors = [];
38

39
    /**
40
     * Convert Ret object to response
41
     *
42
     * @param Req|null $req
43
     * @param Res|null $res
44
     * @return Res
45
     * @throws \Exception
46
     */
47
    public function toRes(Req $req = null, Res $res = null)
48
    {
49
        $req || $req = $this->req;
18✔
50
        $res || $res = $this->res;
18✔
51

52
        $model = $this->getMetadata('model');
18✔
53
        if ($model instanceof BaseModel && $model->wasRecentlyCreated()) {
18✔
54
            $res->setStatusCode(201);
3✔
55
        }
56

57
        if ($req->acceptJson() || $this->isApi($req)) {
18✔
58
            return $res->json($this);
15✔
59
        } else {
60
            $type = $this->data['retType'] ?? ($this->isSuc() ? 'success' : 'warning');
3✔
61
            $content = $this->view->render('@plugin/_ret.php', $this->data + ['type' => $type]);
3✔
62
            return $res->setContent($content);
3✔
63
        }
64
    }
65

66
    /**
67
     * Throw exception if ret is error
68
     *
69
     * @return $this
70
     * @throws RetException
71
     * @experimental
72
     */
73
    public function assert(): ?self
74
    {
NEW
75
        if ($this->isErr()) {
×
NEW
76
            throw new RetException($this);
×
77
        }
NEW
78
        return $this;
×
79
    }
80

81
    /**
82
     * {@inheritDoc}
83
     * @throws \Exception
84
     * @svc
85
     */
86
    protected function err($message, $code = null, $level = null)
87
    {
88
        if (null === $code && !isset($message['code']) && $this->env->isDev()) {
54✔
89
            $code = $this->generateCode($message) ?? $this->defaultErrCode;
3✔
90
        }
91
        return parent::err($message, $code, $level);
54✔
92
    }
93

94
    /**
95
     * @param string|array $message
96
     * @return int|null
97
     * @throws \Exception
98
     * @internal
99
     */
100
    protected function generateCode($message)
101
    {
102
        $traces = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 4);
3✔
103

104
        if ('err' === $traces[3]['function']) {
3✔
105
            // err();
106
            $file = $traces[3]['file'];
×
107
        } else {
108
            // Ret:err();
109
            $file = $traces[2]['file'];
3✔
110
        }
111

112
        $name = $this->getPluginFromFile($file);
3✔
113
        if (!$name) {
3✔
114
            return null;
×
115
        }
116

117
        $plugin = $this->plugin->getOneById($name);
3✔
118
        if (!$plugin->getCode()) {
3✔
119
            return null;
×
120
        }
121

122
        $errors = $this->getErrors($name);
3✔
123
        $key = is_array($message) ? ($message['message'] ?? $message[0]) : $message;
3✔
124
        if (isset($errors[$key])) {
3✔
125
            $code = $errors[$key];
3✔
126
        } else {
127
            $code = (end($errors) ?: $plugin->getCode() * 1000) + 1;
3✔
128
            $errors[$key] = $code;
3✔
129
            $this->setErrors($name, $errors);
3✔
130
        }
131

132
        return $code;
3✔
133
    }
134

135
    /**
136
     * @param string $file
137
     * @return string|null
138
     * @internal
139
     */
140
    protected function getPluginFromFile(string $file): ?string
141
    {
142
        $parts = explode('/plugins/', $file);
×
143
        if (1 === count($parts)) {
×
144
            // Not in plugin
145
            return null;
×
146
        }
147
        return explode('/', $parts[1], 2)[0];
×
148
    }
149

150
    /**
151
     * @param string $name
152
     * @return array
153
     * @internal
154
     */
155
    protected function getErrors(string $name): array
156
    {
157
        if (!isset(static::$errors[$name])) {
3✔
158
            $file = $this->getErrorFile($name);
3✔
159
            if (is_file($file)) {
3✔
160
                static::$errors[$name] = require $file;
×
161
            } else {
162
                static::$errors[$name] = [];
3✔
163
            }
164
        }
165
        return static::$errors[$name];
3✔
166
    }
167

168
    /**
169
     * @param string $name
170
     * @param array $errors
171
     * @internal
172
     */
173
    protected function setErrors(string $name, array $errors): void
174
    {
175
        static::$errors[$name] = $errors;
3✔
176
        $file = $this->getErrorFile($name);
3✔
177
        $dir = dirname($file);
3✔
178
        if (!is_dir($dir)) {
3✔
179
            mkdir($dir);
×
180
        }
181

182
        // Convert to short array syntax
183
        $content = "<?php\n\nreturn [" . substr(var_export($errors, true), strlen('array ('), -1) . "];\n";
3✔
184
        file_put_contents($this->getErrorFile($name), $content);
3✔
185
    }
1✔
186

187
    /**
188
     * @param string $name
189
     * @return string
190
     * @internal
191
     */
192
    protected function getErrorFile(string $name): string
193
    {
194
        return 'plugins/' . $name . '/config/errors.php';
×
195
    }
196

197
    /**
198
     * 判断是否为API接口
199
     *
200
     * @param Req $req
201
     * @return bool
202
     */
203
    private function isApi(Req $req)
204
    {
205
        $pathInfo = $req->getRouterPathInfo();
6✔
206
        $path = explode('/', $pathInfo, 3)[1];
6✔
207
        if ('api' === $path || '-api' === substr($path, -4)) {
6✔
208
            return true;
3✔
209
        }
210
        return false;
3✔
211
    }
212
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc