1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* The brain teaches itself about rive script files. |
5
|
|
|
* |
6
|
|
|
* @package Rivescript-php |
7
|
|
|
* @subpackage Core |
8
|
|
|
* @category Cortex |
9
|
|
|
* @author Shea Lewis <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Axiom\Rivescript\Cortex; |
13
|
|
|
|
14
|
|
|
use Axiom\Rivescript\Exceptions\ParseException; |
15
|
|
|
use Axiom\Rivescript\Rivescript; |
16
|
|
|
use SplFileObject; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* The Brain class. |
20
|
|
|
*/ |
21
|
|
|
class Brain |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* A collection of topics. |
25
|
|
|
* |
26
|
|
|
* @var array<Topic> |
27
|
|
|
*/ |
28
|
|
|
protected $topics; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Create a new instance of Brain. |
32
|
|
|
*/ |
33
|
|
|
public function __construct() |
34
|
|
|
{ |
35
|
|
|
$this->createTopic('random'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Teach the brain contents of a new file source. |
40
|
|
|
* |
41
|
|
|
* @param string $file The Rivescript file to read. |
42
|
|
|
* |
43
|
|
|
* @return void |
44
|
|
|
*/ |
45
|
|
|
public function teach(string $file) |
46
|
|
|
{ |
47
|
|
|
$commands = synapse()->commands; |
48
|
|
|
$script = new SplFileObject($file); |
49
|
|
|
$lastNode = null; |
|
|
|
|
50
|
|
|
$lineNumber = 0; |
51
|
|
|
|
52
|
|
|
while (!$script->eof()) { |
53
|
|
|
$line = $script->fgets(); |
54
|
|
|
$node = new Node($line, $lineNumber++); |
55
|
|
|
|
56
|
|
|
if ($node->isInterrupted() or $node->isComment()) { |
57
|
|
|
continue; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$commands->each(function ($command) use ($node) { |
61
|
|
|
$class = "\\Axiom\\Rivescript\\Cortex\\Commands\\$command"; |
62
|
|
|
$commandClass = new $class(); |
63
|
|
|
$commandClass->parse($node); |
64
|
|
|
}); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
|
69
|
|
|
public function readFromStream($stream) |
|
|
|
|
70
|
|
|
{ |
71
|
|
|
|
72
|
|
|
} |
|
|
|
|
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Return a topic. |
76
|
|
|
* |
77
|
|
|
* @param string|null $name The name of the topic to return. |
78
|
|
|
* |
79
|
|
|
* @return mixed|null |
80
|
|
|
*/ |
81
|
|
|
public function topic(string $name = null) |
82
|
|
|
{ |
83
|
|
|
if (is_null($name)) { |
84
|
|
|
$name = synapse()->memory->shortTerm()->get('topic') ?: 'random'; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
if (!isset($this->topics[$name])) { |
88
|
|
|
return null; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $this->topics[$name]; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* Create a new Topic. |
96
|
|
|
* |
97
|
|
|
* @param string $name The name of the topic to create. |
98
|
|
|
* |
99
|
|
|
* @return Topic |
100
|
|
|
*/ |
101
|
|
|
public function createTopic(string $name): Topic |
102
|
|
|
{ |
103
|
|
|
$this->topics[$name] = new Topic($name); |
104
|
|
|
|
105
|
|
|
return $this->topics[$name]; |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|