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
104  $this->changed[$key] = self::$dbo->quote($value);
105  return $value;
106  }
107 
108  public function save()
109  {
110  \Tools\Hooks::trigger("onBeforeEntitySave");
111  \Tools\Hooks::trigger("onBeforeEntitySave".$this->getTableName());
112  if ($this->id === null)
113  {
114  if (empty ($this->changed))
115  {
116  $query = "INSERT INTO `{$this->getTableName()}` () VALUES ()";
117  $result = self::$dbo->exec($query);
118  if (!$result)
119  throw new \Exception(self::$dbo->errorInfo()[2]);
120  }
121  else
122  {
123  $query = "INSERT INTO `{$this->getTableName()}` (`" .implode("`,`", array_keys($this->changed)) . "`) VALUES (" . implode(",", $this->changed) . ")";
124  $result = self::$dbo->exec($query);
125  if (!$result)
126  throw new \Exception(self::$dbo->errorInfo()[2]);
127  $this->changed = array();
128  }
129  $this->id = self::$dbo->lastInsertId();
130  }
131  else
132  {
133  if (!empty($this->changed))
134  {
135  if ($this->id === false)
136  throw new \Exception("Cannot update private row");
137  $query = "UPDATE {$this->getTableName()} SET ";
138  $newValues = array();
139  foreach ($this->changed as $i => $j)
140  $newValues[] = "`{$i}`=" . $j;
141  $query .= implode(",",$newValues)." WHERE id={$this->id}";
142  $result = self::$dbo->exec($query);
143  if (!$result)
144  throw new \Exception(self::$dbo->errorInfo()[2]);
145  $this->changed = array();
146  }
147  }
148  \Tools\Hooks::trigger("onAfterEntitySave");
149  \Tools\Hooks::trigger("onAfterEntitySave".$this->getTableName());
150  }
151 
152  public function selects($criteria = null, $orderBy = null)
153  {
154  $query = "SELECT * FROM {$this->getTableName()}";
155 
156  if (!empty($criteria))
157  {
158  $subQuery = array();
159  foreach ($criteria as $i => $j)
160  {
161  if ($j == null)
162  $subQuery[] = "`{$i}` IS NULL";
163  else if (is_array($j))
164  {
165  $inArray = [];
166  foreach ($j as $k)
167  $inArray[] = self::$dbo->quote($k);
168  $subQuery[] = "`{$i}` IN (".implode(",", $inArray).")";
169  }
170  else
171  $subQuery[] = "`{$i}`=".self::$dbo->quote($j);
172  }
173  $query .= " WHERE ".implode(" AND ", $subQuery);
174  }
175  if (!empty($orderBy))
176  {
177  $_orderBy = array();
178  foreach ($orderBy as $i => $j)
179  {
180  if (is_numeric($i))
181  $_orderBy[] = "`{$j}` ASC";
182  else
183  {
184  $orderType = "ASC";
185  if (strtoupper($j == "DESC"))
186  $orderType = "DESC";
187  $_orderBy[] = "`{$i}` {$orderType}";
188  }
189  }
190  $query .= " ORDER BY ".implode(",", $_orderBy);
191  }
192  $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
193  if ($result === false)
194  throw new \Exception(self::$dbo->errorInfo()[2]);
195  $resultObj = array();
196  $className = get_class($this);
197  foreach ($result as $i)
198  {
199  $iObj = new $className();
200  $iObj->populate($i);
201  $resultObj[] = $iObj;
202  }
203  return $resultObj;
204  }
205 
206  public function selectById($id)
207  {
208  $query = "SELECT * FROM {$this->getTableName()} WHERE id=".(int)$id." LIMIT 1";
209  $result = self::$dbo->query($query, \PDO::FETCH_ASSOC);
210  if ($result === false || empty($result))
211  throw new \Exception("Cannot fetch data: ".self::$dbo->errorInfo()[2]);
212  $this->populate($result->fetch());
213  }
214 
215  private function populate($data)
216  {
217  $this->id = FALSE;
218  foreach ($data as $i => $j)
219  $this->fieldsValues[$i] = $j;
220  if (isset($this->fieldsValues["id"]))
221  $this->id = (int) $this->fieldsValues["id"];
222  $this->changed = array();
223  }
224 }
225 
static init($config=null)
Definition: ModelBase.php:23
selects($criteria=null, $orderBy=null)
Definition: ModelBase.php:152
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