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 information. |
40
|
|
|
* |
41
|
|
|
* @param resource $stream the stream to read from. |
42
|
|
|
* |
43
|
|
|
* @return void |
44
|
|
|
*/ |
45
|
|
|
public function teach($stream) |
46
|
|
|
{ |
47
|
|
|
$commands = synapse()->commands; |
48
|
|
|
|
49
|
|
|
if (is_resource($stream)) { |
50
|
|
|
$lastNode = null; |
|
|
|
|
51
|
|
|
$lineNumber = 0; |
52
|
|
|
|
53
|
|
|
rewind($stream); |
54
|
|
|
while (!feof($stream)) { |
55
|
|
|
$line = fgets($stream); |
56
|
|
|
$node = new Node($line, $lineNumber++); |
57
|
|
|
|
58
|
|
|
echo "LINE: {$line}"; |
59
|
|
|
|
60
|
|
|
if ($node->isInterrupted() or $node->isComment()) { |
61
|
|
|
continue; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$commands->each(function ($command) use ($node) { |
65
|
|
|
$class = "\\Axiom\\Rivescript\\Cortex\\Commands\\$command"; |
66
|
|
|
$commandClass = new $class(); |
67
|
|
|
$commandClass->parse($node); |
68
|
|
|
}); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Return a topic. |
75
|
|
|
* |
76
|
|
|
* @param string|null $name The name of the topic to return. |
77
|
|
|
* |
78
|
|
|
* @return mixed|null |
79
|
|
|
*/ |
80
|
|
|
public function topic(string $name = null) |
81
|
|
|
{ |
82
|
|
|
if (is_null($name)) { |
83
|
|
|
$name = synapse()->memory->shortTerm()->get('topic') ?: 'random'; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
if (!isset($this->topics[$name])) { |
87
|
|
|
return null; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return $this->topics[$name]; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* Create a new Topic. |
95
|
|
|
* |
96
|
|
|
* @param string $name The name of the topic to create. |
97
|
|
|
* |
98
|
|
|
* @return Topic |
99
|
|
|
*/ |
100
|
|
|
public function createTopic(string $name): Topic |
101
|
|
|
{ |
102
|
|
|
$this->topics[$name] = new Topic($name); |
103
|
|
|
|
104
|
|
|
return $this->topics[$name]; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|