1<?php
2
3
4namespace TableRoller\Generator;
5
6
7use TableRoller\Table\Registry;
8
9class BaseGenerator
10{
11    protected string $template;
12    protected Registry $tables;
13
14    private $allowedFunctions = [
15        'trim', 'ucwords', 'ucfirst', 'lcfirst', 'strotolower', 'strtoupper'
16    ];
17
18    /**
19     * BaseGenerator constructor.
20     * @param string $template
21     * @param Registry $tables
22     */
23    public function __construct(Registry $tables)
24    {
25        $this->tables = $tables;
26    }
27
28    /**
29     * @param string $template
30     */
31    public function setTemplate(string $template): void
32    {
33        $this->template = $template;
34    }
35
36    private function doReplacements(array $match): string
37    {
38        $tableName = $match[1];
39        $fn = null;
40        if (false !== strpos($tableName, '|')) {
41            $parts = explode('|', $tableName);
42            $tableName = $parts[0];
43            $fn = $parts[1];
44        }
45        // simple onetime roll
46        $table = $this->tables->load($tableName);
47        $result = $table->rollOnce();
48
49        if (!empty($fn) && in_array($fn, $this->allowedFunctions)) {
50            $result = $fn($result);
51        }
52
53        return $result;
54    }
55
56    public function generate(): string
57    {
58        if (method_exists($this, 'getTemplate')) {
59            $template = $this->getTemplate();
60        } elseif (!empty($this->template)) {
61            $template = $this->template;
62        }
63
64        if (empty($template)) {
65            throw new \Exception('getTemplate()/template property is empty');
66        }
67
68        return preg_replace_callback('/\[([^]]+)\]/', [$this, 'doReplacements'], $template);
69    }
70
71    public function __toString()
72    {
73        return $this->generate();
74    }
75
76    public function __invoke() : string
77    {
78        return $this->generate();
79    }
80
81
82}