ecom
E-commerce cms
 All Data Structures Namespaces Files Functions Variables
ModelBase.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Entity;
4 
5 abstract class ModelBase
6 {
7  private $fieldsValues = array();
8  protected static $dbo = null;
9  private $changed = array();
10  private static $config = null;
11  private $id;
12 
13  protected abstract function install();
14 
15  public function __construct($id = null)
16  {
17  self::init();
18  $this->id = null;
19  if ($id !== null && is_numeric($id))
20  $this->selectById($id);
21  }
22 
23  public static function init($config = null)
24  {
25  if (self::$dbo !== null)
26  return true;
27  // @codeCoverageIgnoreStart
28  // Load config from written file; this file is created from setup script
29  if ($config === null && self::$config === null)
30  {
31  self::$config = @include("core/config.inc.php");
32  if (empty(self::$config))
33  return false;
34  }
35  // @codeCoverageIgnoreEnd
36  else
37  self::$config = $config;
38  self::$dbo = new \PDO(self::$config[0], self::$config[1], self::$config[2]);
39  return true;
40  }
41 
42  public static function getDbPrefix()
43  {
44  return self::$config[3];
45  }
46 
47  public function getTableName()
48  {
49  $className = new \ReflectionClass($this);
50  return $this->getDbPrefix().strtolower($className->getShortName());
51  }
52 
53  public static function setup()
54  {
55  $tables = array("Admin", "User", "Address", "Cart", "Category", "Product", "CartProduct", "Meta", "Cms", "Config", "Module", "ModuleHook");
56 
57  self::init();
58  self::$dbo->beginTransaction();
59  try
60  {
61  foreach ($tables as $i)
62  {
63  $i = "Entity\\".$i;
64  $table = new $i();
65  if ($table->install() != true)
66  throw new \Exception("{$i}: Cannot table setup failure");
67  }
68  }
69  catch (\Exception $e)
70  {
71  self::$dbo->rollBack();
72  error_log($e->getMessage());
73  return false;
74  }
75  self::$dbo->commit();
76  return true;
77  }
78 
79  public function getMeta($lang=null)
80  {
81  $fetcher = new \Entity\Meta();
82  return $fetcher->query(array("type" => get_class($this)));
83  }
84 
85  public function __get($key)
86  {
87  if ($key == "meta")
88  return $this->getMeta();
89  if ($key == "id")
90  return $this->id === null ? null : (int) $this->id;
91  if (!isset($this->fieldsValues[$key]))
92  return null;
93  return $this->fieldsValues[$key];
94  }
95 
96  public function __set($key, $value)
97  {
98  if ($value instanceof \DateTime)
99  $value = $value->format("Y-m-d");
100  $this->fieldsValues[$key] = $value;
101  if (is_bool($value))
102  $this->changed[$key] = $value ? 1 : 0;
103  else if ($value === null)
104  $this->changed[$key] = "NULL";
105  else
106  $this->changed[$key] = self::$dbo->quote($value);
107  return $value;
108  }
109 
110  public function save()
111  {
112  \Tools\Hooks::trigger("onBeforeEntitySave");
113  \Tools\Hooks::trigger("onBeforeEntitySave".$this->getTableName());
114  if ($this->id === null)
115  {
116  if (empty ($this->changed))
117  {
118  $query = "INSERT INTO `{$this->getTableName()}` () VALUES ()";
119  $result = self::$dbo->exec($query);
120  if (!$result)
121  throw new \Exception(self::$dbo->errorInfo()[2]);
122  }
123  else
124  {
125  $query = "INSERT INTO `{$this->getTableName()}` (`" .implode("`,`", array_keys($this->changed)) . "`) VALUES (" . implode(",", $this->changed) . ")";
126  $result = self::$dbo->exec($query);
127  if (!$result)
128  throw new \Exception(self::$dbo->errorInfo()[2]);
129  $this->changed = array();
130  }
131  $this->id = self::$dbo->lastInsertId();
132  }
133  else
134  {
135  if (!empty($this->changed))
136  {
137  if ($this->id === false)
138  throw new \Exception("Cannot update private row");
139  $query = "UPDATE {$this->getTableName()} SET ";
140  $newValues = array();
141  foreach ($this->changed as $i => $j)
142  $newValues[] = "`{$i}`=" . $j;
143  $query .= implode(",",$newValues)." WHERE id={$this->id}";
144  $result = self::$dbo->exec($query);
145  if (!$result)
146  throw new \Exception(self::$dbo->errorInfo()[2]);
147  $this->changed = array();
148  }
149  }
150  \Tools\Hooks::trigger("onAfterEntitySave");
151  \Tools\Hooks::trigger("onAfterEntitySave".$this->getTableName());
152  }
153 
154  public function selects($criteria = null, $orderBy = null)
155  {
156  $query = "SELECT * FROM {$this->getTableName()}";
157 
158  if (!empty($criteria))
159  {
160  $subQuery = array();
161  foreach ($criteria as $i => $j)
162  {
163  if ($j == null)
164  $subQuery[] = "`{$i}` IS NULL";
165  else if (is_array($j))
166  {
167  $inArray = [];
168  foreach ($j as $k)
169  $inArray[] = self::$dbo->quote($k);
170  $subQuery[] = "`{$i}` IN (".implode(",", $inArray).")";
171  }
172  else
173  $subQuery[] = "`{$i}`=".self::$dbo->quote($j);
174  }
175  $query .= " WHERE ".implode(" AND ", $subQuery);
176  }
177  if (!empty($orderBy))
178  {
179  $_orderBy = array();
180  foreach ($orderBy as $i => $j)
181  {
182  if (is_numeric($i))
183  $_orderBy[] = "`{$j}` ASC";
184  else
185  {
186  $orderType = "ASC";
187  if (strtoupper($j == "DESC"))
188  $orderType = "DESC";
189  $_orderBy[] = "`{$i}` {$orderType}";
190  }
191  }
192  $query .= " ORDER BY ".implode(",", $_orderBy);
193  }
194  $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
195  if ($result === false)
196  throw new \Exception(self::$dbo->errorInfo()[2]);
197  $resultObj = array();
198  $className = get_class($this);
199  foreach ($result as $i)
200  {
201  $iObj = new $className();
202  $iObj->populate($i);
203  $resultObj[] = $iObj;
204  }
205  return $resultObj;
206  }
207 
208  public function selectById($id)
209  {
210  $query = "SELECT * FROM {$this->getTableName()} WHERE id=".(int)$id." LIMIT 1";
211  $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
212  if ($result === false || empty($result))
213  throw new \Exception("Cannot fetch data: ".self::$dbo->errorInfo()[2]);
214  $this->populate($result->fetch());
215  }
216 
217  private function populate($data)
218  {
219  $this->id = FALSE;
220  foreach ($data as $i => $j)
221  $this->fieldsValues[$i] = $j;
222  if (isset($this->fieldsValues["id"]))
223  $this->id = (int) $this->fieldsValues["id"];
224  $this->changed = array();
225  }
226 }
227 
static init($config=null)
Definition: ModelBase.php:23
selects($criteria=null, $orderBy=null)
Definition: ModelBase.php:154
getMeta($lang=null)
Definition: ModelBase.php:79
__set($key, $value)
Definition: ModelBase.php:96
static getDbPrefix()
Definition: ModelBase.php:42
__construct($id=null)
Definition: ModelBase.php:15
static setup()
Definition: ModelBase.php:53
trigger($hookName, $params=null)
Definition: Hooks.php:62