Passed
Push — master ( f62ea3...7ec3d6 )
by Johnny
06:28
created

Rivescript::debugMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of Rivescript-php
4
 *
5
 * (c) Shea Lewis <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Axiom\Rivescript;
12
13
use Axiom\Rivescript\Cortex\ContentLoader\ContentLoader;
14
use Axiom\Rivescript\Cortex\Input;
15
use Axiom\Rivescript\Cortex\Output;
16
use Axiom\Rivescript\Events\Event;
17
use Axiom\Rivescript\Events\EventEmitter;
18
use Axiom\Rivescript\Traits\Tags;
19
20
/**
21
 * Rivescript class
22
 *
23
 * The entry point for using the interpreter.
24
 *
25
 * PHP version 7.4 and higher.
26
 *
27
 * @category Core
28
 * @package  Cortext
29
 * @author   Shea Lewis <[email protected]>
30
 * @license  https://opensource.org/licenses/MIT MIT
31
 * @link     https://github.com/axiom-labs/rivescript-php
32
 * @since    0.3.0
33
 */
34
class Rivescript extends ContentLoader
35
{
36
    use Tags, EventEmitter;
0 ignored issues
show
Bug introduced by
The trait Axiom\Rivescript\Traits\Tags requires the property $memory which is not provided by Axiom\Rivescript\Rivescript.
Loading history...
37
38
39
    public const VERBOSITY_NORMAL = 0;
40
    public const VERBOSITY_VERBOSE = 1;
41
    public const VERBOSITY_VERY_VERBOSE = 2;
42
    public const VERBOSITY_DEBUG = 3;
43
44
    public $onSay = null;
45
    public $onWarn = null;
46
    public $onDebug = null;
47
48
    /**
49
     * A recursion limit before an attempt to
50
     * fetch a reply will be abandoned.
51
     *
52
     * @var int
53
     */
54
    public int $depth = 50;
55
56
    /**
57
     * Error messages.
58
     *
59
     * @var array|string[]
60
     */
61
    public array $errors = [
62
        "replyNotMatched" => "ERR: No Reply Matched",
63
        "replyNotFound" => "ERR: No Reply Found",
64
        "objectNotFound" => "[ERR: Object Not Found]",
65
        "deepRecursion" => "ERR: Deep Recursion Detected"
66
    ];
67
68
    /**
69
     * Flag to indicating if utf8
70
     * modes is enabled.
71
     *
72
     * @var bool
73
     */
74
    protected bool $utf8 = false;
75
76
    /**
77
     * Flag to indicate debug mode
78
     * is enabled or not.
79
     *
80
     * @var bool
81
     */
82
    public bool $debug = false;
83
84
    /**
85
     * This is the user identification.
86
     *
87
     * @var string
88
     */
89
    private string $client_id = 'local-user';
90
91
    /**
92
     * Create a new Rivescript instance.
93
     *
94
     * @param array $options Options for the Rivescript interpreter.
95
     *
96
     * @throws \Axiom\Rivescript\Exceptions\ContentLoadingException
97
     */
98
    public function __construct(array $options = [])
99
    {
100
        parent::__construct();
101
102
        include __DIR__ . '/bootstrap.php';
103
104
        $options;
105
106
        synapse()->brain->setMaster($this);
107
        synapse()->rivescript = $this;
108
109
//        $this->setClientId($this->client_id);
110
        $this->registerTags();
111
    }
112
113
    /**
114
     * Initialize the Tags
115
     *
116
     * @return void
117
     */
118
    private function registerTags(): void
119
    {
120
        synapse()->tags->each(
0 ignored issues
show
Bug Best Practice introduced by
The property tags does not exist on Axiom\Rivescript\Cortex\Synapse. Since you implemented __get, consider adding a @property annotation.
Loading history...
121
            function ($tag) {
122
                $class = "\\Axiom\\Rivescript\\Cortex\\Tags\\$tag";
123
                $tagInstance = new $class();
124
125
                $tagInfo = $tagInstance->getTagName();
126
                if (is_array($tagInfo)) {
127
                    foreach ($tagInfo as $tagName) {
128
                        synapse()->memory->tags()->put($tagName, $tagInstance);
129
                    }
130
                } else {
131
                    synapse()->memory->tags()->put($tagInfo, $tagInstance);
132
                }
133
            }
134
        );
135
    }
136
137
    /**
138
     * Load Rivescript interpretable content.
139
     * Into the Interpreter.
140
     *
141
     * Please note: This supports
142
     *
143
     * - Directory path to Rivescript interpretable files.
144
     * - Array of absolute paths to Rivescript interpretable files
145
     * - Absolute string containing path to Rivescript interpretable file.
146
     * - A stream of text with Rivescript interpretable script.
147
     *
148
     * Please note 2:
149
     *
150
     * If you profile a directory with rivescript documents make sure they are
151
     * all interpretable Rivescript will throw syntax errors while trying to
152
     * parse those files.
153
     *
154
     * @param array<string>|string $info The files to read
155
     *
156
     * @return void
157
     */
158
    public function load($info): void
159
    {
160
        parent::load($info);
161
        $this->processInformation();
162
    }
163
164
    /**
165
     * Stream new information into the brain.
166
     *
167
     * @param string $string The string of information to feed the brain.
168
     *
169
     * @return void
170
     */
171
    public function stream(string $string): void
172
    {
173
        fseek($this->getStream(), 0, SEEK_SET);
174
        rewind($this->getStream());
175
176
        $this->writeToMemory($string);
177
        $this->processInformation();
178
    }
179
180
    /**
181
     * Process new information in the
182
     * stream.
183
     *
184
     * @return void
185
     */
186
    private function processInformation(): void
187
    {
188
        synapse()->memory->local()->put('concat', 'none');
189
        synapse()->brain->teach($this->getStream());
190
    }
191
192
    /**
193
     * Set the client id.
194
     *
195
     * @param string $client_id The client id for this user.
196
     *
197
     * @return void
198
     */
199
    public function setClientId(string $client_id = 'local-user'): void
200
    {
201
        $this->client_id = $client_id;
202
    }
203
204
    /**
205
     * Return the client id.
206
     *
207
     * @return string
208
     */
209
    public function getClientId(): string
210
    {
211
        return $this->client_id;
212
    }
213
214
    /**
215
     * Set user variables.
216
     *
217
     * @param string $name  The name of the variable.
218
     * @param string $value The value of the variable.
219
     *
220
     * @return void
221
     */
222
    public function set_uservar(string $name, string $value): void
223
    {
224
        synapse()->memory->user($this->client_id)->put($name, $value);
225
    }
226
227
    /**
228
     * Get user variable.
229
     *
230
     * @param string $name The name of the variable.
231
     *
232
     * @return mixed
233
     */
234
    public function get_uservar(string $name)
235
    {
236
        return synapse()->memory->user($this->client_id)->get($name) ?? "undefined";
237
    }
238
239
    /**
240
     * Log a message to say.
241
     *
242
     * @param string $message   The message to print out.
243
     * @param array  $args      (format) arguments for the message.
244
     * @param int    $verbosity The verbosity level of the message.
245
     *
246
     * @return void
247
     */
248
    public function say(string $message, array $args = [], int $verbosity = Rivescript::VERBOSITY_NORMAL): void
0 ignored issues
show
Unused Code introduced by
The parameter $verbosity is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

248
    public function say(string $message, array $args = [], /** @scrutinizer ignore-unused */ int $verbosity = Rivescript::VERBOSITY_NORMAL): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
249
    {
250
251
        $message = $this->formatString($message, $args);
252
253
        $this->emit(EVENT::DEBUG_VERBOSE, $message);
254
    }
255
256
    /**
257
     * Write a debug message.
258
     *
259
     * @param string $message   The message to print out.
260
     * @param array  $args      (format) arguments for the message.
261
     * @param int    $verbosity The verbosity level of the message.
262
     *
263
     * @return void
264
     */
265
    public function warn(string $message,
0 ignored issues
show
Coding Style introduced by
The first parameter of a multi-line function declaration must be on the line after the opening bracket
Loading history...
266
                         array  $args = [],
0 ignored issues
show
Coding Style introduced by
Multi-line function declaration not indented correctly; expected 8 spaces but found 25
Loading history...
267
                         int    $verbosity = Rivescript::VERBOSITY_DEBUG): void
0 ignored issues
show
Unused Code introduced by
The parameter $verbosity is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

267
                         /** @scrutinizer ignore-unused */ int    $verbosity = Rivescript::VERBOSITY_DEBUG): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
The closing parenthesis of a multi-line function declaration must be on a new line
Loading history...
Coding Style introduced by
Multi-line function declaration not indented correctly; expected 8 spaces but found 25
Loading history...
268
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
269
        $message = "[WARNING]: " . $this->formatString($message, $args);
270
271
        $this->emit(Event::DEBUG_WARNING, $message);
272
    }
273
274
    /**
275
     * Write a warning.
276
     *
277
     * @param string $message   The message to print out.
278
     * @param array  $args      (format) arguments for the message.
279
     * @param int    $verbosity The verbosity level of the message.
280
     *
281
     * @return void
282
     */
283
    public function debug(string $message,
0 ignored issues
show
Coding Style introduced by
The first parameter of a multi-line function declaration must be on the line after the opening bracket
Loading history...
284
                          array  $args = [],
0 ignored issues
show
Coding Style introduced by
Multi-line function declaration not indented correctly; expected 8 spaces but found 26
Loading history...
285
                          int    $verbosity = Rivescript::VERBOSITY_NORMAL): void
0 ignored issues
show
Coding Style introduced by
The closing parenthesis of a multi-line function declaration must be on a new line
Loading history...
Coding Style introduced by
Multi-line function declaration not indented correctly; expected 8 spaces but found 26
Loading history...
Unused Code introduced by
The parameter $verbosity is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

285
                          /** @scrutinizer ignore-unused */ int    $verbosity = Rivescript::VERBOSITY_NORMAL): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
286
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
287
        $message = "[DEBUG]: " . $this->formatString($message, $args);
288
289
        $this->emit(EVENT::DEBUG, $message);
290
    }
291
292
293
    /**
294
     * Create a string PDO style/
295
     *
296
     * @param string $msg  The message to write.
297
     * @param array[]  $args The arguments for the message.
298
     *
299
     * @return string
300
     */
301
    private function formatString(string $msg, array $args = []): string
302
    {
303
        $search = [];
304
        $replace = [];
305
306
        if (is_array($args) === true && count($args) > 0) {
307
            foreach ($args as $key => $value) {
308
                $search [] = ":{$key}";
309
                $replace [] = $value;
310
            }
311
312
            $msg = str_replace($search, $replace, $msg);
313
        }
314
315
        return $msg;
316
    }
317
318
    /**
319
     * Enable debug mode.
320
     *
321
     * @param bool $status Set debug mode status.
322
     *
323
     * @return void
324
     */
325
    public function debugMode(bool $status = false): void
326
    {
327
        synapse()->memory->global()->put('debug', $status);
328
    }
329
330
    /**
331
     * Enable or disable utf8 mode.
332
     *
333
     * @param bool $status
334
     *
335
     * @return void
336
     */
337
    public function utf8(bool $status = false): void
338
    {
339
        $this->utf8 = $status;
340
    }
341
342
    public function isUtf8Enabled(): bool
343
    {
344
        return ($this->utf8 === true);
345
    }
346
347
    /**
348
     * Make the client respond to a message.
349
     *
350
     * @param string      $msg   The message the client has to process and respond to.
351
     * @param string      $user  The user id.
352
     * @param string|null $scope Not used at this point.
353
     *
354
     * @return string
355
     */
356
    public function reply(string $msg, string $user = 'local-user', string $scope = null): string
0 ignored issues
show
Unused Code introduced by
The parameter $scope is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

356
    public function reply(string $msg, string $user = 'local-user', /** @scrutinizer ignore-unused */ string $scope = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
357
    {
358
359
        // FIXME: Must be $user, $message, Sscope
360
        //    $msg = $this->stripNasties($msg, "");
361
        synapse()->rivescript->say("Asked to reply to :user :msg", ['user' => $user, 'msg' => $msg]);
362
363
364
        $input = new Input($msg, $user);
365
        $output = new Output();
366
367
        synapse()->input = $input;
368
369
        $output = $output->process();
370
371
        if (empty($output)) {
372
            $output = $this->errors['replyNotMatched'];
373
        }
374
375
        synapse()->memory->inputs()->push($msg);
376
        synapse()->memory->replies()->push($output);
377
378
        return $output;
379
    }
380
}
381