Passed
Pull Request — master (#2)
by Johnny
03:52 queued 02:03
created

Trigger::determineWordCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
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\Cortex\Commands;
12
13
use Axiom\Rivescript\Cortex\ResponseQueue\ResponseQueue;
14
use Axiom\Rivescript\Contracts\Command;
15
use Axiom\Rivescript\Cortex\Node;
16
17
/**
18
 * Trigger class
19
 *
20
 * This class handles the Trigger command (+ ...)
21
 * and stores the definition in memory.
22
 *
23
 * PHP version 7.4 and higher.
24
 *
25
 * @category Core
26
 * @package  Cortext\Commands
27
 * @author   Shea Lewis <[email protected]>
28
 * @license  https://opensource.org/licenses/MIT MIT
29
 * @link     https://github.com/axiom-labs/rivescript-php
30
 * @since    0.3.0
31
 */
32
class Trigger implements Command
33
{
34
    /**
35
     * Parse the command.
36
     *
37
     * @param Node $node The node is a line from the Rivescript file.
38
     *
39
     * @return void
40
     */
41
    public function parse(Node $node): void
42
    {
43
        if ($node->command() === '+') {
44
            $topic = synapse()->memory->shortTerm()->get('topic') ?: 'random';
45
            $topic = synapse()->brain->topic($topic);
46
            $type = $this->determineTriggerType($node->value());
47
48
            $data = [
49
                'type' => $type,
50
                'responses' => new ResponseQueue($node->value()),
51
            ];
52
53
            $topic->triggers->put($node->value(), $data);
54
            $topic->triggers = $topic->sortTriggers($topic->triggers());
55
56
            synapse()->memory->shortTerm()->put('trigger', $node->value());
57
        }
58
    }
59
60
    /**
61
     * Determine the type of trigger to aid in sorting.
62
     *
63
     * @param string $trigger The trigger to parse.
64
     *
65
     * @return string
66
     */
67
    protected function determineTriggerType(string $trigger): string
68
    {
69
        $wildcards = [
70
            'alphabetic' => '/_/',
71
            'numeric' => '/#/',
72
            'global' => '/\*/',
73
        ];
74
75
        foreach ($wildcards as $type => $pattern) {
76
            if (@preg_match_all($pattern, $trigger, $stars)) {
77
                return $type;
78
            }
79
        }
80
81
        return 'atomic';
82
    }
83
}
84