Ubiquity  2.0.3
php rapid development framework
ControllersTrait.php
Go to the documentation of this file.
1 <?php
2 
4 
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 public function _refreshControllers($refresh = false);
36 
37  abstract protected function _createController($controllerName,$variables=[],$ctrlTemplate='controller.tpl',$hasView=false,$jsCallback="");
38 
39  abstract protected function _addMessageForRouteCreation($path);
40 
41  abstract public function showSimpleMessage($content, $type, $title=null,$icon="info", $timeout=NULL, $staticName=null):HtmlMessage;
42 
43  public function createController($force=null) {
44  if (URequest::isPost()) {
45  $this->_createController($_POST["name"],["%baseClass%"=>"ControllerBase"],'controller.tpl',isset($_POST["lbl-ck-div-name"]));
46  }
47  $this->controllers();
48  }
49 
50  public function _createView() {
51  if (URequest::isPost()) {
52  $action=$_POST["action"];
53  $controller=$_POST["controller"];
54  $controllerFullname=$_POST["controllerFullname"];
55  $viewName=$controller . "/" . $action . ".html";
56  $this->_createViewOp($controller, $action);
57  if (\file_exists(ROOT . DS . "views" . DS . $viewName)) {
58  $this->jquery->exec('$("#msgControllers").transition("show");$("#msgControllers .content").transition("show").append("<br><b>' . $viewName . '</b> created !");', true);
59  }
60  $r=new \ReflectionMethod($controllerFullname, $action);
61  $lines=file($r->getFileName());
62  $views=$this->_getAdminViewer()->getActionViews($controllerFullname, $controller, $action, $r, $lines);
63  foreach ( $views as $view ) {
64  echo $view->compile($this->jquery);
65  echo "&nbsp;";
66  }
67  echo $this->jquery->compile($this->view);
68  }
69  }
70 
71  private function _createViewOp($controller, $action) {
72  $viewName=$controller . "/" . $action . ".html";
73  UFileSystem::safeMkdir(ROOT . DS . "views" . DS . $controller);
74  $frameworkDir=Startup::getFrameworkDir();
75  UFileSystem::openReplaceWriteFromTemplateFile($frameworkDir . "/admin/templates/view.tpl", ROOT . DS . "views" . DS . $viewName, [ "%controllerName%" => $controller,"%actionName%" => $action ]);
76  return $viewName;
77  }
78 
79  public function _newActionFrm() {
80  if (URequest::isPost()) {
81  $controllers=CacheManager::getControllers();
82  $controller=$_POST["controller"];
83  $modal=$this->jquery->semantic()->htmlModal("modalNewAction", "Creating a new action in controller");
84  $modal->setInverted();
85  $frm=$this->jquery->semantic()->htmlForm("frmNewAction");
86  $dd=$frm->addDropdown('controller', \array_combine($controllers, $controllers), "Controller", $controller);
87  $dd->getField()->setShowOnFocus(false);
88  $fields=$frm->addFields([ "action","parameters" ], "Action & parameters");
89  $fields->getItem(0)->addRules([ "empty",[ "checkAction","Action {value} already exists!" ] ]);
90  $frm->addTextarea("content", "Implementation")->addRule([ "checkContent","Errors parsing action content!" ]);
91  ;
92  $frm->addCheckbox("ck-view", "Create associated view");
93  $frm->addCheckbox("ck-add-route", "Add route...");
94 
95  $frm->addContent("<div id='div-new-route' style='display: none;'>");
96  $frm->addDivider();
97  $fields=$frm->addFields();
98  $fields->addInput("path", "", "text", "")->addRule([ "checkRoute","Route {value} already exists!" ]);
99  $fields->addDropdown("methods", Constants::REQUEST_METHODS, null, "", true);
100  $duration=$fields->addInput("duration", "", "number");
101  $ck=$duration->labeledCheckbox("left", null);
102  $ck->getField()->setProperty("name", "ck-Cache");
103  $frm->addContent("</div>");
104 
105  $frm->setValidationParams([ "on" => "blur","inline" => true ]);
106  $frm->setSubmitParams($this->_getAdminFiles()->getAdminBaseRoute() . "/_newAction", "#messages");
107  $modal->setContent($frm);
108  $modal->addAction("Validate");
109  $this->jquery->click("#action-modalNewAction-0", "$('#frmNewAction').form('submit');", false, false);
110  $modal->addAction("Close");
111  $this->jquery->exec("$('.dimmer.modals.page').html('');$('#modalNewAction').modal('show');", true);
112  $this->jquery->jsonOn("change", "#ck-add-route", $this->_getAdminFiles()->getAdminBaseRoute() . "/_addRouteWithNewAction", "post", [ "context" => "$('#frmNewAction')","params" => "$('#frmNewAction').serialize()","jsCondition" => "$('#ck-add-route').is(':checked')" ]);
113  $this->jquery->exec(Rule::ajax($this->jquery, "checkAction", $this->_getAdminFiles()->getAdminBaseRoute() . "/_methodExists", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
114  $this->jquery->exec(Rule::ajax($this->jquery, "checkContent", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkContent", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
115  $this->jquery->exec(Rule::ajax($this->jquery, "checkRoute", $this->_getAdminFiles()->getAdminBaseRoute() . "/_checkRoute", "{}", "result=data.result;", "postForm", [ "form" => "frmNewAction" ]), true);
116  $this->jquery->change("#ck-add-route", "$('#div-new-route').toggle($(this).is(':checked'));");
117  echo $modal;
118  echo $this->jquery->compile($this->view);
119  }
120  }
121 
122  public function _controllerExists($fieldname) {
123  if (URequest::isPost()) {
124  $result=[ ];
125  header('Content-type: application/json');
126  $controller=ucfirst($_POST[$fieldname]);
127  $controllerNS=Startup::getNS("controllers");
128  $result["result"]=!class_exists($controllerNS.$controller);
129  echo json_encode($result);
130  }
131  }
132 
133  public function _methodExists() {
134  if (URequest::isPost()) {
135  $result=[ ];
136  header('Content-type: application/json');
137  $controller=$_POST["controller"];
138  $action=$_POST["action"];
139  if (\method_exists($controller, $action)) {
140  $result["result"]=false;
141  } else {
142  $result["result"]=true;
143  }
144  echo json_encode($result);
145  }
146  }
147 
148  public function _checkContent() {
149  if (URequest::isPost()) {
150  $result=[ ];
151  header('Content-type: application/json');
152  $content=$_POST["content"];
153  $result["result"]=CodeUtils::isValidCode('<?php ' . $content);
154  echo json_encode($result);
155  }
156  }
157 
158  public function _checkRoute() {
159  if (URequest::isPost()) {
160  $result=[ ];
161  header('Content-type: application/json');
162  $path=$_POST["path"];
163  $routes=CacheManager::getRoutes();
164  $result["result"]=!(isset($routes[$path]) || Router::getRouteInfo($path) !== false);
165  echo json_encode($result);
166  }
167  }
168 
169  public function _addRouteWithNewAction() {
170  if (URequest::isPost()) {
171  $result=[ ];
172  header('Content-type: application/json');
173 
174  $controller=$_POST["controller"];
175  $action=$_POST["action"];
176  $parameters=$_POST["parameters"];
177  $parameters=CodeUtils::getParametersForRoute($parameters);
178  $controller=ClassUtils::getClassSimpleName($controller);
179 
180  $urlParts=\array_diff(\array_merge([ $controller,$action ], $parameters), [ "","{}" ]);
181  $result["path"]=\implode('/', $urlParts);
182  echo json_encode($result);
183  }
184  }
185 
186  public function _newAction() {
187  if (URequest::isPost()) {
188  $frameworkDir=Startup::getFrameworkDir();
189  $msgContent="";
190  $controller=$_POST["controller"];
191  $r=new \ReflectionClass($controller);
192  $ctrlFilename=$r->getFileName();
193  $action=$_POST["action"];
194  $parameters=$_POST["parameters"];
195  $content=$_POST["content"];
196  $content=CodeUtils::indent($content, 2);
197  $createView=isset($_POST["ck-view"]);
198  $createRoute=isset($_POST["ck-add-route"]);
199  $fileContent=\implode("", UIntrospection::getClassCode($controller));
200  $fileContent=\trim($fileContent);
201  $posLast=\strrpos($fileContent, "}");
202  if ($posLast !== false) {
203  if ($createView) {
204  $viewname=$this->_createViewOp(ClassUtils::getClassSimpleName($controller), $action);
205  $content.="\n\t\t\$this->loadView('" . $viewname . "');\n";
206  $msgContent.="<br>Created view : <b>" . $viewname . "</b>";
207  }
208  $routeAnnotation="";
209  if ($createRoute) {
210  $name="route";
211  $path=$_POST["path"];
212  $routeProperties=[ '"' . $path . '"' ];
213  $methods=$_POST["methods"];
214  if (UString::isNotNull($methods)) {
215  $routeProperties[]='"methods"=>' . $this->getMethods($methods);
216  }
217  if (isset($_POST["ck-Cache"])) {
218  $routeProperties[]='"cache"=>true';
219  if (isset($_POST["duration"])) {
220  $duration=$_POST["duration"];
221  if (\ctype_digit($duration)) {
222  $routeProperties[]='"duration"=>' . $duration;
223  }
224  }
225  }
226  $routeProperties=\implode(",", $routeProperties);
227  $routeAnnotation=UFileSystem::openReplaceInTemplateFile($frameworkDir . "/admin/templates/annotation.tpl", [ "%name%" => $name,"%properties%" => $routeProperties ]);
228 
229  $msgContent.=$this->_addMessageForRouteCreation($path);
230  }
231  $parameters=CodeUtils::cleanParameters($parameters);
232  $actionContent=UFileSystem::openReplaceInTemplateFile($frameworkDir . "/admin/templates/action.tpl", [ "%route%" => "\n" . $routeAnnotation,"%actionName%" => $action,"%parameters%" => $parameters,"%content%" => $content ]);
233  $fileContent=\substr_replace($fileContent, "\n%content%", $posLast - 1, 0);
234  if (!CodeUtils::isValidCode('<?php ' . $content)) {
235  echo $this->showSimpleMessage("Errors parsing action content!", "warning","Creation", "warning circle", null, "msgControllers");
236  echo $this->jquery->compile($this->view);
237  return;
238  } else {
239  if (UFileSystem::replaceWriteFromContent($fileContent . "\n", $ctrlFilename, [ '%content%' => $actionContent ])) {
240  $msgContent="The action <b>{$action}</b> is created in controller <b>{$controller}</b>" . $msgContent;
241  echo $this->showSimpleMessage($msgContent, "info","Creation", "info circle", null, "msgControllers");
242  }
243  }
244  }
245  }
246  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/_refreshControllers/refresh", "#dtControllers", [ "jqueryDone" => "replaceWith","hasLoader" => false,"dataType" => "html" ]);
247  echo $this->jquery->compile($this->view);
248  }
249 
250  public function _refreshCacheControllers() {
251  $config=Startup::getConfig();
252  \ob_start();
253  CacheManager::initCache($config, "controllers");
254  $message=\ob_get_clean();
255  echo $this->showSimpleMessage(\nl2br($message), "info", "info", 4000);
256  $this->jquery->get($this->_getAdminFiles()->getAdminBaseRoute() . "/_refreshControllers/refresh", "#dtControllers", [ "jqueryDone" => "replaceWith","hasLoader" => false,"dataType" => "html" ]);
257  echo $this->jquery->compile($this->view);
258  }
259 
260  private function getMethods($strMethods) {
261  $methods=\explode(",", $strMethods);
262  $result=[ ];
263  foreach ( $methods as $method ) {
264  $result[]='"' . $method . '"';
265  }
266  return "[" . \implode(",", $result) . "]";
267  }
268 
269  public function frmFilterControllers(){
270  $controllers=CacheManager::getControllers();
271  $this->_getAdminViewer()->getFilterControllers($controllers);
272  $this->jquery->postFormOn("click", "#validate-btn", $this->_getAdminFiles()->getAdminBaseRoute()."/filterControllers", "filtering-frm","#dtControllers",["jqueryDone" => "replaceWith","hasLoader" => false,"jsCallback"=>'$("#frm").html("");']);
273  $this->jquery->execOn("click", "#cancel-btn", '$("#frm").html("");');
274  $this->jquery->renderView($this->_getAdminFiles()->getViewControllersFiltering());
275  }
276 
277  protected function _createClass($template,$classname,$namespace,$uses,$extendsOrImplements,$classContent){
278  $namespaceVar="";
279  if(UString::isNotNull($namespace)){
280  $namespaceVar="namespace {$namespace};";
281  }
282  $variables=["%classname%"=>$classname,"%namespace%"=>$namespaceVar,"%uses%"=>$uses,"%extendsOrImplements%"=>$extendsOrImplements,"%classContent%"=>$classContent];
283  $frameworkDir = Startup::getFrameworkDir ();
284  $directory=UFileSystem::getDirFromNamespace($namespace);
285  UFileSystem::safeMkdir($directory);
286  $filename=UFileSystem::cleanFilePathname($directory.DS.lcfirst($classname).".php");
287  if(!file_exists($filename)){
288  UFileSystem::openReplaceWriteFromTemplateFile ( $frameworkDir . "/admin/templates/" . $template, $filename, $variables );
289  $message = $this->showSimpleMessage ( "The <b>" . $classname . "</b> class has been created in <b>" . $filename . "</b>.", "success","Creation", "checkmark circle");
290  }else{
291  $message = $this->showSimpleMessage ( "The file <b>" . $filename . "</b> already exists.<br>Can not create the <b>" . $classname . "</b> class!", "warning","Creation", "warning circle");
292  }
293  return $message;
294  }
295 
296  protected function _createMethod($access,$name,$parameters="",$return="",$content="",$comment=""){
297  $frameworkDir = Startup::getFrameworkDir ();
298  $keyAndValues=["%access%"=>$access,"%name%"=>$name,"%parameters%"=>$parameters,"%content%"=>$content,"%comment%"=>$comment,"%return%"=>$return];
299  return UFileSystem::openReplaceInTemplateFile($frameworkDir . "/admin/templates/method.tpl" , $keyAndValues);
300  }
301 
302  public function filterControllers(){
303  USession::set("filtered-controllers", URequest::post("filtered-controllers",[]));
304  $this->_refreshControllers("refresh");
305  }
306 }
showSimpleMessage($content, $type, $title=null, $icon="info", $timeout=NULL, $staticName=null)
static isPost()
Returns true if the request is sent by the POST method.
Definition: URequest.php:109
static getRouteInfo($path)
Definition: Router.php:74
static post($key, $default=NULL)
Returns the value of the $key variable passed by the post method or $default if the $key variable doe...
Definition: URequest.php:146
static getNS($part="controllers")
Definition: Startup.php:45
static set($key, $value)
Adds or sets a value to the Session at position $key.
Definition: USession.php:151
static openReplaceWriteFromTemplateFile($source, $destination, $keyAndValues)
Definition: UFileSystem.php:73
static openReplaceInTemplateFile($source, $keyAndValues)
Definition: UFileSystem.php:65
static getControllers($subClass="\biquity\ontrollers\ontroller", $backslash=false, $includeSubclass=false)
_createMethod($access, $name, $parameters="", $return="", $content="", $comment="")
static replaceWriteFromContent($content, $destination, $keyAndValues)
Definition: UFileSystem.php:89
_createController($controllerName, $variables=[], $ctrlTemplate='controller.tpl', $hasView=false, $jsCallback="")
_createClass($template, $classname, $namespace, $uses, $extendsOrImplements, $classContent)
static initCache(&$config, $type="all", $silent=false)
static getClassSimpleName($classnameWithNamespace)
Definition: ClassUtils.php:135