Ubiquity  2.0.0
php rapid development framework
ModelsTrait.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use Ajax\JsUtils;
15 
22 
23  abstract public function _getAdminData();
24 
25  abstract public function _getAdminViewer();
26 
27  abstract public function _getAdminFiles();
28 
29  abstract protected function showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null);
30 
31  public function showTable($table) {
32  $this->_showTable($table);
33  $model=$this->getModelsNS() . "\\" . ucfirst($table);
34  $this->_getAdminViewer()->getModelsStructureDataTable(OrmUtils::getModelMetadata($model));
35  $bt=$this->jquery->semantic()->htmlButton("btYuml", "Class diagram");
36  $bt->postOnClick($this->_getAdminFiles()->getAdminBaseRoute() . "/_showDiagram/", "{model:'" . \str_replace("\\", "|", $model) . "'}", "#modal", [ "attr" => "" ]);
37  $this->jquery->exec('$("#models-tab .item").tab();', true);
38  $this->jquery->compile($this->view);
39  $this->loadView($this->_getAdminFiles()->getViewShowTable(), [ "classname" => $model ]);
40  }
41 
42  public function refreshTable() {
43  $table=$_SESSION["table"];
44  echo $this->_showTable($table);
45  echo $this->jquery->compile($this->view);
46  }
47 
48  public function showTableClick($tableAndId) {
49  $array=\explode(".", $tableAndId);
50  if (\is_array($array)) {
51  $table=$array[0];
52  $id=$array[1];
53  $this->jquery->exec("$('#menuDbs .active').removeClass('active');$('.ui.label.left.pointing.teal').removeClass('left pointing teal active');$(\"[data-ajax='" . $table . "']\").addClass('active');$(\"[data-ajax='" . $table . "']\").find('.ui.label').addClass('left pointing teal');", true);
54  $this->showTable($table);
55  $this->jquery->exec("$(\"tr[data-ajax='" . $id . "']\").click();", true);
56  echo $this->jquery->compile();
57  }
58  }
59 
60  protected function _showTable($table) {
61  $_SESSION["table"]=$table;
62  $model=$this->getModelsNS() . "\\" . ucfirst($table);
63  $datas=DAO::getAll($model);
64  return $this->_getAdminViewer()->getModelDataTable($datas, $model);
65  }
66 
67  protected function _edit($instance, $modal="no") {
68  $_SESSION["instance"]=$instance;
69  $modal=($modal == "modal");
70  $form=$this->_getAdminViewer()->getForm("frmEdit", $instance);
71  $this->jquery->click("#action-modal-frmEdit-0", "$('#frmEdit').form('submit');", false);
72  if (!$modal) {
73  $this->jquery->click("#bt-cancel", "$('#form-container').transition('drop');");
74  $this->jquery->compile($this->view);
75  $this->loadView($this->_getAdminFiles()->getViewEditTable(), [ "modal" => $modal ]);
76  } else {
77  $this->jquery->exec("$('#modal-frmEdit').modal('show');", true);
78  $form=$form->asModal(\get_class($instance));
79  $form->setActions([ "Okay","Cancel" ]);
80  $btOkay=$form->getAction(0);
81  $btOkay->addClass("green")->setValue("Validate modifications");
82  $form->onHidden("$('#modal-frmEdit').remove();");
83  echo $form->compile($this->jquery, $this->view);
84  echo $this->jquery->compile($this->view);
85  }
86  }
87 
88  public function edit($modal="no", $ids="") {
89  $instance=$this->getModelInstance($ids);
90  $instance->_new=false;
91  $this->_edit($instance, $modal);
92  }
93 
94  public function newModel($modal="no") {
95  $model=$this->getModelsNS() . "\\" . ucfirst($_SESSION["table"]);
96  $instance=new $model();
97  $instance->_new=true;
98  $this->_edit($instance, $modal);
99  }
100 
101  public function update() {
102  $message=$this->jquery->semantic()->htmlMessage("msgUpdate", "Modifications were successfully saved", "info");
103  $instance=@$_SESSION["instance"];
104  $className=\get_class($instance);
105  $relations=OrmUtils::getManyToOneFields($className);
106  $fieldTypes=OrmUtils::getFieldTypes($className);
107  foreach ( $fieldTypes as $property => $type ) {
108  if ($type == "tinyint(1)") {
109  if (isset($_POST[$property])) {
110  $_POST[$property]=1;
111  } else {
112  $_POST[$property]=0;
113  }
114  }
115  }
116  URequest::setValuesToObject($instance, $_POST);
117  foreach ( $relations as $member ) {
118  if ($this->_getAdminData()->getUpdateManyToOneInForm()) {
119  $joinColumn=OrmUtils::getAnnotationInfoMember($className, "#joinColumn", $member);
120  if ($joinColumn) {
121  $fkClass=$joinColumn["className"];
122  $fkField=$joinColumn["name"];
123  if (isset($_POST[$fkField])) {
124  $fkObject=DAO::getOne($fkClass, $_POST["$fkField"]);
125  Reflexion::setMemberValue($instance, $member, $fkObject);
126  }
127  }
128  }
129  }
130  if (isset($instance)) {
131  if ($instance->_new) {
132  $update=DAO::insert($instance);
133  } else {
134  $update=DAO::update($instance);
135  if (DbCache::$active) {
136  // TODO update dbCache
137  }
138  }
139  if ($update) {
140  if ($this->_getAdminData()->getUpdateManyToManyInForm()) {
141  $relations=OrmUtils::getManyToManyFields($className);
142  foreach ( $relations as $member ) {
143  if (($annot=OrmUtils::getAnnotationInfoMember($className, "#manyToMany", $member)) !== false) {
144  $newField=$member . "Ids";
145  $fkClass=$annot["targetEntity"];
146  $fkObjects=DAO::getAll($fkClass, $this->getMultiWhere($_POST[$newField], $className));
147  if (Reflexion::setMemberValue($instance, $member, $fkObjects)) {
148  DAO::insertOrUpdateManyToMany($instance, $member);
149  }
150  }
151  }
152  }
153  $message->setStyle("success")->setIcon("checkmark");
154  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/refreshTable", "#lv", [ "jqueryDone" => "replaceWith" ]);
155  } else {
156  $message->setContent("An error has occurred. Can not save changes.")->setStyle("error")->setIcon("warning circle");
157  }
158  echo $message;
159  echo $this->jquery->compile($this->view);
160  }
161  }
162 
163  private function getPks($model) {
164  $instance=new $model();
165  return OrmUtils::getKeyFields($instance);
166  }
167 
168  private function getMultiWhere($ids, $class) {
169  $pk=OrmUtils::getFirstKey($class);
170  $ids=explode(",", $ids);
171  if (sizeof($ids) < 1)
172  return "";
173  $strs=[ ];
174  $idCount=\sizeof($ids);
175  for($i=0; $i < $idCount; $i++) {
176  $strs[]=$pk . "='" . $ids[$i] . "'";
177  }
178  return implode(" OR ", $strs);
179  }
180 
181  private function getOneWhere($ids, $table) {
182  $ids=explode("_", $ids);
183  if (sizeof($ids) < 1)
184  return "";
185  $pks=$this->getPks(ucfirst($table));
186  $strs=[ ];
187  $idCount=\sizeof($ids);
188  for($i=0; $i < $idCount; $i++) {
189  $strs[]=$pks[$i] . "='" . $ids[$i] . "'";
190  }
191  return implode(" AND ", $strs);
192  }
193 
194  private function getModelInstance($ids) {
195  $table=$_SESSION['table'];
196  $model=$this->getModelsNS() . "\\" . ucfirst($table);
197  $ids=\explode("_", $ids);
198  return DAO::getOne($model, $ids);
199  }
200 
201  public function delete($ids) {
202  $instance=$this->getModelInstance($ids);
203  if (method_exists($instance, "__toString"))
204  $instanceString=$instance . "";
205  else
206  $instanceString=get_class($instance);
207  if (sizeof($_POST) > 0) {
208  if (DAO::remove($instance)) {
209  $message=$this->showSimpleMessage("Deletion of `<b>" . $instanceString . "</b>`", "info", "info", 4000);
210  $this->jquery->exec("$('tr[data-ajax={$ids}]').remove();", true);
211  } else {
212  $message=$this->showSimpleMessage("Can not delete `" . $instanceString . "`", "warning", "warning");
213  }
214  } else {
215  $message=$this->showConfMessage("Do you confirm the deletion of `<b>" . $instanceString . "</b>`?", "error", $this->_getAdminFiles()->getAdminBaseRoute() . "/delete/{$ids}", "#table-messages", $ids);
216  }
217  echo $message;
218  echo $this->jquery->compile($this->view);
219  }
220 
221  private function getFKMethods($model) {
222  $reflection=new \ReflectionClass($model);
223  $publicMethods=$reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
224  $result=[ ];
225  foreach ( $publicMethods as $method ) {
226  $methodName=$method->getName();
227  if (JString::startswith($methodName, "get")) {
228  $attributeName=lcfirst(JString::replaceAtFirst($methodName, "get", ""));
229  if (!property_exists($model, $attributeName))
230  $result[]=$methodName;
231  }
232  }
233  return $result;
234  }
235 
236  public function showDetail($ids) {
237  $viewer=$this->_getAdminViewer();
238  $hasElements=false;
239  $instance=$this->getModelInstance($ids);
240  $table=$_SESSION['table'];
241  $model=$this->getModelsNS() . "\\" . ucfirst($table);
242  $relations=OrmUtils::getFieldsInRelations($model);
243  $semantic=$this->jquery->semantic();
244  $grid=$semantic->htmlGrid("detail");
245  if (sizeof($relations) > 0) {
246  $wide=intval(16 / sizeof($relations));
247  if ($wide < 4)
248  $wide=4;
249  foreach ( $relations as $member ) {
250  if (($annot=OrmUtils::getAnnotationInfoMember($model, "#oneToMany", $member)) !== false) {
251  $objectFK=DAO::getOneToMany($instance, $member);
252  $fkClass=$annot["className"];
253  } elseif (($annot=OrmUtils::getAnnotationInfoMember($model, "#manyToMany", $member)) !== false) {
254  $objectFK=DAO::getManyToMany($instance, $member);
255  $fkClass=$annot["targetEntity"];
256  } else {
257  $objectFK=Reflexion::getMemberValue($instance, $member);
258  if (isset($objectFK))
259  $fkClass=\get_class($objectFK);
260  }
261  if (isset($fkClass)) {
262  $fkTable=OrmUtils::getTableName($fkClass);
263  $memberFK=$member;
264 
265  $header=new HtmlHeader("", 4, $memberFK, "content");
266  if (is_array($objectFK) || $objectFK instanceof \Traversable) {
267  $header=$viewer->getFkHeaderList($memberFK, $fkClass, $objectFK);
268  $element=$viewer->getFkList($memberFK, $fkClass, $objectFK);
269  foreach ( $objectFK as $item ) {
270  if (method_exists($item, "__toString")) {
271  $id=($this->getIdentifierFunction($fkClass))(0, $item);
272  $item=$element->addItem($item . "");
273  $item->setProperty("data-ajax", $fkTable . "." . $id);
274  $item->addClass("showTable");
275  $hasElements=true;
276  $this->_getAdminViewer()->displayFkElementList($item, $memberFK, $fkClass, $item);
277  }
278  }
279  } else {
280  if (method_exists($objectFK, "__toString")) {
281  $header=$viewer->getFkHeaderElement($memberFK, $fkClass, $objectFK);
282  $id=($this->getIdentifierFunction($fkClass))(0, $objectFK);
283  $element=$viewer->getFkElement($memberFK, $fkClass, $objectFK);
284  $element->setProperty("data-ajax", $fkTable . "." . $id)->addClass("showTable");
285  }
286  }
287  if (isset($element)) {
288  $grid->addCol($wide)->setContent($header . $element);
289  $hasElements=true;
290  }
291  }
292  }
293  if ($hasElements)
294  echo $grid;
295  $this->jquery->getOnClick(".showTable", $this->_getAdminFiles()->getAdminBaseRoute() . "/showTableClick", "#divTable", [ "attr" => "data-ajax","ajaxTransition" => "random" ]);
296  echo $this->jquery->compile($this->view);
297  }
298  }
299 
300  protected function getModelsNS() {
301  return Startup::getConfig()["mvcNS"]["models"];
302  }
303 
304  private function _getCks($array) {
305  $result=[ ];
306  foreach ( $array as $dataAjax => $caption ) {
307  $result[]=$this->_getCk($caption, $dataAjax);
308  }
309  return $result;
310  }
311 
312  private function _getCk($caption, $dataAjax) {
313  $ck=new HtmlCheckbox("ck-" . $dataAjax, $caption, "1");
314  $ck->setProperty("name", "ck[]");
315  $ck->setProperty("data-ajax", $dataAjax);
316  return $ck;
317  }
318 }
static getFieldsInRelations($class)
Definition: OrmUtils.php:222
static getOne($className, $keyValues, $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an instance of $className from the database, from $keyvalues values of the primary key...
Definition: DAO.php:348
static getAnnotationInfoMember($class, $keyAnnotation, $member)
Definition: OrmUtils.php:200
static setValuesToObject($object, $values=null)
Affects member to member the values of the associative array $values to the members of the object $ob...
Definition: URequest.php:21
static setMemberValue($instance, $member, $value)
Definition: Reflexion.php:41
static insertOrUpdateManyToMany($instance, $member)
Updates the $member member of $instance annotated by a ManyToMany.
static getFirstKey($class)
Definition: OrmUtils.php:121
showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null)
static getManyToMany($instance, $member, $array=null, $useCache=NULL)
Assigns / loads the child records in the $member member of $instance.
Definition: DAO.php:127
static getAll($className, $condition='', $loadManyToOne=true, $loadOneToMany=false, $useCache=NULL)
Returns an array of $className objects from the database.
Definition: DAO.php:193
static getMemberValue($instance, $member)
Definition: Reflexion.php:35
static getFieldTypes($className)
Definition: OrmUtils.php:85
static getModelMetadata($className)
Definition: OrmUtils.php:18
static getManyToManyFields($class)
Definition: OrmUtils.php:240
static getTableName($class)
Definition: OrmUtils.php:61
static getOneToMany($instance, $member, $useCache=NULL, $annot=null)
Assign / load the child records in the $member member of $instance.
Definition: DAO.php:71
static getManyToOneFields($class)
Definition: OrmUtils.php:236
static getKeyFields($instance)
Definition: OrmUtils.php:71
static remove($instance)
Deletes the object $instance from the database.
static update($instance, $updateMany=false)
Updates an existing $instance in the database.
static insert($instance, $insertMany=false)
Inserts a new instance $ instance into the database.