Ubiquity  2.0.0
php rapid development framework
ControllersTrait.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use Ajax\JsUtils;
19 
27 
28  abstract public function _getAdminData();
29 
30  abstract public function _getAdminViewer();
31 
32  abstract public function _getAdminFiles();
33 
34  abstract public function controllers();
35 
36  abstract protected function _createController($controllerName,$variables=[],$ctrlTemplate='controller.tpl',$hasView=false);
37 
38  abstract protected function _addMessageForRouteCreation($path);
39 
40  abstract public function showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null);
41 
42  public function createController($force=null) {
43  if (URequest::isPost()) {
44  $this->_createController($_POST["name"],[],'controller.tpl',isset($_POST["lbl-ck-div-name"]));
45  }
46  $this->controllers();
47  }
48 
49  public function _createView() {
50  if (URequest::isPost()) {
51  $action=$_POST["action"];
52  $controller=$_POST["controller"];
53  $controllerFullname=$_POST["controllerFullname"];
54  $viewName=$controller . "/" . $action . ".html";
55  $this->_createViewOp($controller, $action);
56  if (\file_exists(ROOT . DS . "views" . DS . $viewName)) {
57  $this->jquery->exec('$("#msgControllers").transition("show");$("#msgControllers .content").transition("show").append("<br><b>' . $viewName . '</b> created !");', true);
58  }
59  $r=new \ReflectionMethod($controllerFullname, $action);
60  $lines=file($r->getFileName());
61  $views=$this->_getAdminViewer()->getActionViews($controllerFullname, $controller, $action, $r, $lines);
62  foreach ( $views as $view ) {
63  echo $view->compile($this->jquery);
64  echo "&nbsp;";
65  }
66  echo $this->jquery->compile($this->view);
67  }
68  }
69 
70  private function _createViewOp($controller, $action) {
71  $viewName=$controller . "/" . $action . ".html";
72  UFileSystem::safeMkdir(ROOT . DS . "views" . DS . $controller);
73  $frameworkDir=Startup::getFrameworkDir();
74  UFileSystem::openReplaceWriteFromTemplateFile($frameworkDir . "/admin/templates/view.tpl", ROOT . DS . "views" . DS . $viewName, [ "%controllerName%" => $controller,"%actionName%" => $action ]);
75  return $viewName;
76  }
77 
78  public function _newActionFrm() {
79  if (URequest::isPost()) {
80  $controllers=CacheManager::getControllers();
81  $controller=$_POST["controller"];
82  $modal=$this->jquery->semantic()->htmlModal("modalNewAction", "Creating a new action in controller");
83  $modal->setInverted();
84  $frm=$this->jquery->semantic()->htmlForm("frmNewAction");
85  $dd=$frm->addDropdown('controller', \array_combine($controllers, $controllers), "Controller", $controller);
86  $dd->getField()->setShowOnFocus(false);
87  $fields=$frm->addFields([ "action","parameters" ], "Action & parameters");
88  $fields->getItem(0)->addRules([ "empty",[ "checkAction","Action {value} already exists!" ] ]);
89  $frm->addTextarea("content", "Implementation")->addRule([ "checkContent","Errors parsing action content!" ]);
90  ;
91  $frm->addCheckbox("ck-view", "Create associated view");
92  $frm->addCheckbox("ck-add-route", "Add route...");
93 
94  $frm->addContent("<div id='div-new-route' style='display: none;'>");
95  $frm->addDivider();
96  $fields=$frm->addFields();
97  $fields->addInput("path", "", "text", "")->addRule([ "checkRoute","Route {value} already exists!" ]);
98  $fields->addDropdown("methods", Constants::REQUEST_METHODS, null, "", true);
99  $duration=$fields->addInput("duration", "", "number");
100  $ck=$duration->labeledCheckbox("left", null);
101  $ck->getField()->setProperty("name", "ck-Cache");
102  $frm->addContent("</div>");
103 
104  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
105  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/_newAction", "#messages");
106  $modal->setContent($frm);
107  $modal->addAction("Validate");
108  $this->jquery->click("#action-modalNewAction-0", "$('#frmNewAction').form('submit');", false, false);
109  $modal->addAction("Close");
110  $this->jquery->exec("$('.dimmer.modals.page').html('');$('#modalNewAction').modal('show');", true);
111  $this->jquery->jsonOn("change", "#ck-add-route", $this->_getAdminFiles()->getAdminBaseRoute() . "/_addRouteWithNewAction", "post", [ "context" => "$('#frmNewAction')","params" => "$('#frmNewAction').serialize()","jsCondition" => "$('#ck-add-route').is(':checked')" ]);
112  $this->jquery->exec(Rule::ajax($this->jquery, "checkAction", $this->_getAdminFiles()->getAdminBaseRoute() . "/_methodExists", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
113  $this->jquery->exec(Rule::ajax($this->jquery, "checkContent", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkContent", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
114  $this->jquery->exec(Rule::ajax($this->jquery, "checkRoute", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkRoute", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
115  $this->jquery->change("#ck-add-route", "$('#div-new-route').toggle($(this).is(':checked'));");
116  echo $modal;
117  echo $this->jquery->compile($this->view);
118  }
119  }
120 
121  public function _methodExists() {
122  if (URequest::isPost()) {
123  $result=[ ];
124  header('Content-type: application/json');
125  $controller=$_POST["controller"];
126  $action=$_POST["action"];
127  if (\method_exists($controller, $action)) {
128  $result["result"]=false;
129  } else {
130  $result["result"]=true;
131  }
132  echo json_encode($result);
133  }
134  }
135 
136  public function _checkContent() {
137  if (URequest::isPost()) {
138  $result=[ ];
139  header('Content-type: application/json');
140  $content=$_POST["content"];
141  $result["result"]=CodeUtils::isValidCode('<?php ' . $content);
142  echo json_encode($result);
143  }
144  }
145 
146  public function _checkRoute() {
147  if (URequest::isPost()) {
148  $result=[ ];
149  header('Content-type: application/json');
150  $path=$_POST["path"];
151  $routes=CacheManager::getRoutes();
152  $result["result"]=!(isset($routes[$path]) || Router::getRouteInfo($path) !== false);
153  echo json_encode($result);
154  }
155  }
156 
157  public function _addRouteWithNewAction() {
158  if (URequest::isPost()) {
159  $result=[ ];
160  header('Content-type: application/json');
161 
162  $controller=$_POST["controller"];
163  $action=$_POST["action"];
164  $parameters=$_POST["parameters"];
165  $parameters=CodeUtils::getParametersForRoute($parameters);
166  $controller=ClassUtils::getClassSimpleName($controller);
167 
168  $urlParts=\array_diff(\array_merge([ $controller,$action ], $parameters), [ "","{}" ]);
169  $result["path"]=\implode('/', $urlParts);
170  echo json_encode($result);
171  }
172  }
173 
174  public function _newAction() {
175  if (URequest::isPost()) {
176  $frameworkDir=Startup::getFrameworkDir();
177  $msgContent="";
178  $controller=$_POST["controller"];
179  $r=new \ReflectionClass($controller);
180  $ctrlFilename=$r->getFileName();
181  $action=$_POST["action"];
182  $parameters=$_POST["parameters"];
183  $content=$_POST["content"];
184  $content=CodeUtils::indent($content, 2);
185  $createView=isset($_POST["ck-view"]);
186  $createRoute=isset($_POST["ck-add-route"]);
187  $fileContent=\implode("", UIntrospection::getClassCode($controller));
188  $fileContent=\trim($fileContent);
189  $posLast=\strrpos($fileContent, "}");
190  if ($posLast !== false) {
191  if ($createView) {
192  $viewname=$this->_createViewOp(ClassUtils::getClassSimpleName($controller), $action);
193  $content.="\n\t\t\$this->loadView('" . $viewname . "');\n";
194  $msgContent.="<br>Created view : <b>" . $viewname . "</b>";
195  }
196  $routeAnnotation="";
197  if ($createRoute) {
198  $name="route";
199  $path=$_POST["path"];
200  $routeProperties=[ '"' . $path . '"' ];
201  $methods=$_POST["methods"];
202  if (UString::isNotNull($methods)) {
203  $routeProperties[]='"methods"=>' . $this->getMethods($methods);
204  }
205  if (isset($_POST["ck-Cache"])) {
206  $routeProperties[]='"cache"=>true';
207  if (isset($_POST["duration"])) {
208  $duration=$_POST["duration"];
209  if (\ctype_digit($duration)) {
210  $routeProperties[]='"duration"=>' . $duration;
211  }
212  }
213  }
214  $routeProperties=\implode(",", $routeProperties);
215  $routeAnnotation=UFileSystem::openReplaceInTemplateFile($frameworkDir . "/admin/templates/annotation.tpl", [ "%name%" => $name,"%properties%" => $routeProperties ]);
216 
217  $msgContent.=$this->_addMessageForRouteCreation($path);
218  }
219  $parameters=CodeUtils::cleanParameters($parameters);
220  $actionContent=UFileSystem::openReplaceInTemplateFile($frameworkDir . "/admin/templates/action.tpl", [ "%route%" => "\n" . $routeAnnotation,"%actionName%" => $action,"%parameters%" => $parameters,"%content%" => $content ]);
221  $fileContent=\substr_replace($fileContent, "\n%content%", $posLast - 1, 0);
222  if (!CodeUtils::isValidCode('<?php ' . $content)) {
223  echo $this->showSimpleMessage("Errors parsing action content!", "warning", "warning circle", null, "msgControllers");
224  echo $this->jquery->compile($this->view);
225  return;
226  } else {
227  if (UFileSystem::replaceWriteFromContent($fileContent . "\n", $ctrlFilename, [ '%content%' => $actionContent ])) {
228  $msgContent="The action <b>{$action}</b> is created in controller <b>{$controller}</b>" . $msgContent;
229  echo $this->showSimpleMessage($msgContent, "info", "info circle", null, "msgControllers");
230  }
231  }
232  }
233  }
234  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/_refreshControllers/refresh", "#dtControllers", [ "jqueryDone" => "replaceWith","hasLoader" => false,"dataType" => "html" ]);
235  echo $this->jquery->compile($this->view);
236  }
237 
238  public function _refreshCacheControllers() {
239  $config=Startup::getConfig();
240  \ob_start();
241  CacheManager::initCache($config, "controllers");
242  $message=\ob_get_clean();
243  echo $this->showSimpleMessage(\nl2br($message), "info", "info", 4000);
244  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/_refreshControllers/refresh", "#dtControllers", [ "jqueryDone" => "replaceWith","hasLoader" => false,"dataType" => "html" ]);
245  echo $this->jquery->compile($this->view);
246  }
247 
248  private function getMethods($strMethods) {
249  $methods=\explode(",", $strMethods);
250  $result=[ ];
251  foreach ( $methods as $method ) {
252  $result[]='"' . $method . '"';
253  }
254  return "[" . \implode(",", $result) . "]";
255  }
256 }
static isPost()
Returns true if the request is sent by the POST method.
Definition: URequest.php:91
_createController($controllerName, $variables=[], $ctrlTemplate='controller.tpl', $hasView=false)
static getRouteInfo($path)
Definition: Router.php:73
static openReplaceWriteFromTemplateFile($source, $destination, $keyAndValues)
Definition: UFileSystem.php:56
static openReplaceInTemplateFile($source, $keyAndValues)
Definition: UFileSystem.php:48
showSimpleMessage($content, $type, $icon="info", $timeout=NULL, $staticName=null)
static replaceWriteFromContent($content, $destination, $keyAndValues)
Definition: UFileSystem.php:72
static initCache(&$config, $type="all", $silent=false)
static getClassSimpleName($classnameWithNamespace)
Definition: ClassUtils.php:129