flush
[pharext/pharext.org] / app / Cli / GenModels.php
1 <?php
2
3 namespace app\Cli;
4
5 use app\Controller;
6 use app\Model;
7 use pq\Connection;
8
9 class GenModels implements Controller
10 {
11 private $pq;
12
13 function __construct(Connection $pq) {
14 $this->pq = $pq;
15 }
16
17 function __invoke(array $args = null) {
18 $tables = $this->pq->exec("SELECT tablename FROM pg_tables WHERE schemaname='public'");
19 /* @var $tables \pq\Result */
20 foreach ($tables->fetchAllCols("tablename") as $table) {
21 $this->genModel($table);
22 }
23 }
24
25 function genModel($entity) {
26 $title = ucwords($entity);
27 $single = substr($title, -3) == "ies"
28 ? substr($title, 0, -3)."y"
29 : rtrim($title, "s");
30 $this->genTable($entity, $title, $single."Collection");
31 $this->genRowset($single."Collection", $single);
32 $this->genRow($single);
33 }
34
35 function genTable($name, $class, $collection) {
36 $ns = explode("\\", $class);
37
38 if (count($ns) > 1) {
39 $class = array_pop($ns);
40 $dir = implode("/", $ns);
41 $ns = "\\".implode("\\", $ns);
42 } else {
43 $ns = "";
44 $dir = "";
45 }
46
47 $file = __DIR__."/../Model/$dir/$class.php";
48
49 if (!file_exists($file)) {
50 file_put_contents($file, <<<EOD
51 <?php
52
53 namespace app\\Model$ns;
54
55 use pq\\Gateway\\Table;
56
57 class $class extends Table
58 {
59 protected \$name = "$name";
60 protected \$rowset = "app\\\\Model$ns\\\\$collection";
61 }
62
63 EOD
64 );
65 }
66 }
67
68 function genRowset($class, $row) {
69 $ns = explode("\\", $class);
70
71 if (count($ns) > 1) {
72 $class = array_pop($ns);
73 $dir = implode("/", $ns);
74 $ns = "\\".implode("\\", $ns);
75 } else {
76 $ns = "";
77 $dir = "";
78 }
79
80 $file = __DIR__."/../Model/$dir/$class.php";
81
82 if (!file_exists($file)) {
83 file_put_contents($file, <<<EOD
84 <?php
85
86 namespace app\\Model$ns;
87
88 use pq\\Gateway\\Rowset;
89
90 class $class extends Rowset
91 {
92 protected \$row = "app\\\\Model$ns\\\\$row";
93 }
94
95 EOD
96 );
97 }
98 }
99 function genRow($class) {
100 $ns = explode("\\", $class);
101
102 if (count($ns) > 1) {
103 $class = array_pop($ns);
104 $dir = implode("/", $ns);
105 $ns = "\\".implode("\\", $ns);
106 } else {
107 $ns = "";
108 $dir = "";
109 }
110
111 $file = __DIR__."/../Model/$dir/$class.php";
112
113 if (!file_exists($file)) {
114 file_put_contents($file, <<<EOD
115 <?php
116
117 namespace app\\Model$ns;
118
119 use pq\\Gateway\\Row;
120
121 class $class extends Row
122 {
123 }
124
125 EOD
126 );
127 }
128 }
129
130 }