php8
[web.mtrack] / MTrack / Enumeration.php
1 <?php
2
3
4 class MTrackEnumeration {
5   public $tablename;
6   protected $fieldname;
7   protected $fieldvalue;
8
9   public $name = null;
10   public $value = null;
11   public $deleted = null;
12   public $new = true;
13
14   function enumerate($all = false) {
15     $res = array();
16     if ($all) {
17       foreach (MTrackDB::q(sprintf("select %s, %s, deleted from %s order by %s",
18             $this->fieldname, $this->fieldvalue, $this->tablename,
19             $this->fieldvalue))
20             ->fetchAll(PDO::FETCH_NUM)
21           as $row) {
22         $res[$row[0]] = array(
23           'name' => $row[0],
24           'value' => $row[1],
25           'deleted' => $row[2] == '1' ? true : false
26         );
27       }
28     } else {
29       foreach (MTrackDB::q(sprintf("select %s from %s where deleted != '1'",
30               $this->fieldname, $this->tablename))->fetchAll(PDO::FETCH_NUM)
31           as $row) {
32         $res[$row[0]] = $row[0];
33       }
34     }
35     return $res;
36   }
37
38   function __construct($name = null) {
39     if ($name !== null) {
40       list($row) = MTrackDB::q(sprintf(
41           "select %s, deleted from %s where %s = ?",
42           $this->fieldvalue, $this->tablename, $this->fieldname),
43           $name)
44           ->fetchAll();
45       if (isset($row[0])) {
46         $this->name = $name;
47         $this->value = $row[0];
48         $this->deleted = $row[1];
49         $this->new = false;
50         return;
51       }
52       throw new Exception("unable to find $this->tablename with name = $name");
53     }
54
55     $this->deleted = false;
56   }
57
58   function save(MTrackChangeset $CS) {
59     if ($this->new) {
60       MTrackDB::q(sprintf('insert into %s (%s, %s, deleted) values (?, ?, ?)',
61         $this->tablename, $this->fieldname, $this->fieldvalue),
62             $this->name, $this->value, (int)$this->deleted);
63       $old = null;
64     } else {
65       list($row) = MTrackDB::q(
66         sprintf('select %s, deleted from %s where %s = ?',
67           $this->fieldname, $this->tablename, $this->fieldvalue),
68           $this->name)->fetchAll();
69       $old = $row[0];
70       MTrackDB::q(sprintf('update %s set %s = ?, deleted = ? where %s = ?',
71         $this->tablename, $this->fieldvalue, $this->fieldname),
72             $this->value, (int)$this->deleted, $this->name);
73     }
74     $CS->add($this->tablename . ":" . $this->name . ":" . $this->fieldvalue,
75       $old, $this->value);
76
77   }
78 }
79
80
81 /// various enumerations..
82
83
84