1 <?php
2 
3 namespace TableRoller\Table;
4 
5 class Manager
6 {
7 	static private $embedCalls = 0;
8 
9 	public function __construct(
10 		private \helper_plugin_sqlite $db
11 	){}
12 
13 	private static array $tables;
14 
15 	public function rollOn(string $name): string
16 	{
17 		$table = $this->getTable($name);
18 		$result = $table->rollOnce();
19 		return preg_replace_callback('/{{roll on:\s*([A-Za-z0-9_]+)\s*}}/i', [$this, 'embedResult'], $result);
20 	}
21 
22 	private function embedResult($matches): string
23 	{
24 		self::$embedCalls++;
25 		if (self::$embedCalls < 20) {
26 			$table = $this->getTable($matches[1]);
27 			return trim($table->rollOnce());
28 		}
29 
30 		return "Too many recursive calls";
31 	}
32 
33 	private function getTable(string $name): TableInterface
34 	{
35 		if (!isset(self::$tables[$name])) {
36 			$result = $this->db->query('SELECT * FROM rtables WHERE id=? LIMIT 1', $name);
37 			$row = $this->db->res_fetch_assoc($result);
38 			if ($row['rows']) {
39 				self::$tables[$name] = new DokuwikiJsonTable($row['rows']);
40 			} else {
41 				self::$tables[$name] = new BaseTable();
42 			}
43 		}
44 
45 		return self::$tables[$name];
46 	}
47 }
48