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