Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
ScaffoldController.php
Go to the documentation of this file.
1<?php
3
17
28abstract class ScaffoldController extends HasUsesTrait {
29
30 protected $config;
31
32 protected $activeDb;
33
34 public static $views = [
35 "CRUD" => [
36 "index" => "@framework/crud/index.html",
37 "form" => "@framework/crud/form.html",
38 "display" => "@framework/crud/display.html"
39 ],
40 "indexCRUD" => [
41 "index" => "@framework/crud/index.html",
42 "form" => "@framework/crud/form.html",
43 "display" => "@framework/crud/display.html",
44 "home" => "@framework/crud/home.html",
45 "itemHome" => "@framework/crud/itemHome.html",
46 "nav" => "@framework/crud/nav.html"
47 ],
48 "auth" => [
49 "index" => "@framework/auth/index.html",
50 "info" => "@framework/auth/info.html",
51 "noAccess" => "@framework/auth/noAccess.html",
52 "disconnected" => "@framework/auth/disconnected.html",
53 "message" => "@framework/auth/message.html",
54 "create" => "@framework/auth/create.html",
55 "stepTwo" => "@framework/auth/stepTwo.html",
56 "badTwoFACode" => "@framework/auth/badTwoFACode.html",
57 "baseTemplate" => "@framework/auth/baseTemplate.html",
58 "initRecovery" => "@framework/auth/initRecovery.html",
59 "recovery" => "@framework/auth/recovery.html"
60 ]
61 ];
62
63 public function getTemplateDir() {
64 return \dirname(__DIR__) . "/scaffolding/templates/";
65 }
66
67 public function _refreshRest($refresh = false) {}
68
69 public function initRestCache($refresh = true) {}
70
71 protected abstract function storeControllerNameInSession($controller);
72
73 public abstract function showSimpleMessage($content, $type, $title = null, $icon = "info", $timeout = NULL, $staticName = null);
74
75 protected abstract function _addMessageForRouteCreation($path, $jsCallback = "");
76
77 public function _createMethod($access, $name, $parameters = "", $return = "", $content = "", $comment = "") {
78 $templateDir = $this->getTemplateDir();
79 $keyAndValues = [
80 "%access%" => $access,
81 "%name%" => $name,
82 "%parameters%" => $parameters,
83 "%content%" => $content,
84 "%comment%" => $comment,
85 "%return%" => $return
86 ];
87 return UFileSystem::openReplaceInTemplateFile($templateDir . "method.tpl", $keyAndValues);
88 }
89
90 public function getInitialize() {
91 $domain = DDDManager::getActiveDomain();
92 $initialize = '';
93 if ($domain != '') {
94 $initialize = "\n\tpublic function initialize(){\n\t\tparent::initialize();\n\t\t\Ubiquity\domains\DDDManager::setDomain('" . $domain . "');\n\t}";
95 }
96 return $initialize;
97 }
98
99 public function _createController($controllerName, $variables = [], $ctrlTemplate = 'controller.tpl', $hasView = false, $jsCallback = "") {
100 $message = "";
101 $templateDir = $this->getTemplateDir();
102 $controllersNS = \rtrim(Startup::getNS('controllers'), "\\");
103 $controllersDir = \ROOT . \DS . str_replace("\\", \DS, $controllersNS);
104 $controllerName = \ucfirst($controllerName);
105 $filename = $controllersDir . \DS . $controllerName . ".php";
106 if (\file_exists($filename) === false) {
107 $namespace = "";
108 if ($controllersNS !== '') {
109 $namespace = 'namespace ' . $controllersNS . ';';
110 }
111 $msgView = '';
112 $indexContent = '';
113 if ($hasView) {
114 $viewDir = DDDManager::getActiveViewFolder() . $controllerName . \DS;
115 UFileSystem::safeMkdir($viewDir);
116 $viewName = $viewDir . \DS . 'index.html';
117 UFileSystem::openReplaceWriteFromTemplateFile($templateDir . 'view.tpl', $viewName, [
118 '%controllerName%' => $controllerName,
119 '%actionName%' => "index"
120 ]);
121 $msgView = "<br>The default view associated has been created in <b>" . UFileSystem::cleanPathname($viewDir) . "</b>";
122 $indexContent = "\$this->loadView(\"" . DDDManager::getViewNamespace() . $controllerName . "/index.html\");";
123 }
124 $variables = \array_merge([
125 '%controllerName%' => $controllerName,
126 '%indexContent%' => $indexContent,
127 '%namespace%' => $namespace,
128 '%initialize%' => $this->getInitialize(),
129 '%route%' => '',
130 '%uses%' => ''
131 ], $variables);
132 UFileSystem::openReplaceWriteFromTemplateFile($templateDir . $ctrlTemplate, $filename, $variables);
133 $msgContent = "The <b>" . $controllerName . "</b> controller has been created in <b>" . UFileSystem::cleanFilePathname($filename) . "</b>." . $msgView;
134 if (isset($variables['%routePath%']) && $variables['%routePath%'] !== '') {
135 $msgContent .= $this->_addMessageForRouteCreation($variables['%routePath%'], $jsCallback);
136 }
137 $this->storeControllerNameInSession($controllersNS . "\\" . $controllerName);
138 $message = $this->showSimpleMessage($msgContent, 'success', null, 'checkmark circle', NULL, 'msgGlobal');
139 } else {
140 $message = $this->showSimpleMessage("The file <b>" . $filename . "</b> already exists.<br>Can not create the <b>" . $controllerName . "</b> controller!", "warning", null, "warning circle", 100000, "msgGlobal");
141 }
142 return $message;
143 }
144
145 public function addCrudController($crudControllerName, $resource, $crudDatas = null, $crudViewer = null, $crudEvents = null, $crudViews = null, $routePath = '', $useViewInheritance = false, $style = '') {
146 $crudController = new CrudControllerCreator($crudControllerName, $resource, $crudDatas, $crudViewer, $crudEvents, $crudViews, $routePath, $useViewInheritance, $style);
147 $crudController->create($this);
148 }
149
150 public function addIndexCrudController($crudControllerName, $crudDatas = null, $crudViewer = null, $crudEvents = null, $crudViews = null, $routePath = '', $useViewInheritance = false, $style = '') {
151 $crudController = new IndexCrudControllerCreator($crudControllerName, $crudDatas, $crudViewer, $crudEvents, $crudViews, $routePath, $useViewInheritance, $style);
152 $crudController->create($this);
153 }
154
155 public function addAuthController($authControllerName, $baseClass, $authViews = null, $routePath = "", $useViewInheritance = false) {
156 $authCreator = new AuthControllerCreator($authControllerName, $baseClass, $authViews, $routePath, $useViewInheritance);
157 $authCreator->create($this);
158 }
159
160 public function addRestController($restControllerName, $baseClass, $resource, $routePath = "", $reInit = true) {
161 $restCreator = new RestControllerCreator($restControllerName, $baseClass, $resource, $routePath);
162 $restCreator->create($this, $reInit);
163 }
164
165 public function _createClass($template, $classname, $namespace, $uses, $extendsOrImplements, $classContent) {
166 $namespaceVar = '';
167 if (UString::isNotNull($namespace)) {
168 $namespaceVar = "namespace {$namespace};";
169 }
170 $variables = [
171 '%classname%' => $classname,
172 '%namespace%' => $namespaceVar,
173 '%uses%' => $uses,
174 '%extendsOrImplements%' => $extendsOrImplements,
175 '%classContent%' => $classContent,
176 '%classAttributes%'=>''
177 ];
178 $templateDir = $this->getTemplateDir();
179 $directory = UFileSystem::getDirFromNamespace($namespace);
180 UFileSystem::safeMkdir($directory);
181 $filename = UFileSystem::cleanFilePathname($directory . \DS . $classname . '.php');
182 if (! file_exists($filename)) {
183 UFileSystem::openReplaceWriteFromTemplateFile($templateDir . $template, $filename, $variables);
184 $message = $this->showSimpleMessage("The <b>" . $classname . "</b> class has been created in <b>" . $filename . "</b>.", "success", "Creation", "checkmark circle");
185 } else {
186 $message = $this->showSimpleMessage("The file <b>" . $filename . "</b> already exists.<br>Can not create the <b>" . $classname . "</b> class!", "warning", "Creation", "warning circle");
187 }
188 return $message;
189 }
190
191 public function _newAction($controller, $action, $parameters = null, $content = '', $routeInfo = null, $createView = false, $theme = null) {
192 $templateDir = $this->getTemplateDir();
193 $msgContent = "";
194 $r = new \ReflectionClass($controller);
195 if (! \method_exists($controller, $action)) {
196 $ctrlFilename = $r->getFileName();
197 $content = CodeUtils::indent($content, 2);
198 $classCode = UIntrospection::getClassCode($controller);
199 if ($classCode !== false) {
200 $fileContent = \implode('', $classCode);
201 $fileContent = \trim($fileContent);
202 $ctrlName = ClassUtils::getClassSimpleName($controller);
203 if ($createView) {
204 $viewname = $this->_createViewOp($ctrlName, $action, $theme);
205 $content .= "\n\t\t\$this->loadView('" . $viewname . "');\n";
206 $msgContent .= "<br>Created view : <b>" . $viewname . "</b>";
207 }
208 if ($routeInfo != null) {
209 $routeInfo['path'] = $this->generateRoutePath($routeInfo['path'], $ctrlName, $action, $parameters);
210 }
211 $routeAnnotation = $this->generateRouteAnnotation($routeInfo, $ctrlName, $action);
212
213 if ($routeAnnotation != '') {
214 $msgContent .= $this->_addMessageForRouteCreation($routeInfo["path"]);
215 if (\count($this->getUses()) > 0) {
216 $namespace = 'namespace ' . $r->getNamespaceName() . ";";
217 $posUses = \strpos($fileContent, $namespace);
218 if ($posUses !== false) {
219 $posUses += \strlen($namespace) + 1;
220 $uses = $this->uses;
221 foreach ($uses as $use => $_) {
222 if (\strpos($fileContent, 'use ' . $use) !== false) {
223 unset($this->uses[$use]);
224 }
225 }
226 if (\count($this->getUses()) > 0) {
227 $fileContent = \substr_replace($fileContent, "\n" . $this->getUsesStr(), $posUses - 1, 0);
228 }
229 }
230 }
231 }
232 $parameters = CodeUtils::cleanParameters($parameters);
233 $actionContent = UFileSystem::openReplaceInTemplateFile($templateDir . "action.tpl", [
234 '%route%' => "\n\t" . $routeAnnotation ?? '',
235 '%actionName%' => $action,
236 '%parameters%' => $parameters,
237 '%content%' => $content
238 ]);
239 $posLast = \strrpos($fileContent, '}');
240 $fileContent = \substr_replace($fileContent, "\n%content%", $posLast - 1, 0);
241 if (! CodeUtils::isValidCode('<?php ' . $content)) {
242 echo $this->showSimpleMessage("Errors parsing action content!", "warning", "Creation", "warning circle", null, "msgControllers");
243 return;
244 } else {
245 if (UFileSystem::replaceWriteFromContent($fileContent . "\n", $ctrlFilename, [
246 '%content%' => $actionContent
247 ])) {
248 $msgContent = "The action <b>{$action}</b> is created in controller <b>{$controller}</b>" . $msgContent;
249 echo $this->showSimpleMessage($msgContent, "success", "Creation", "info circle", null, "msgControllers");
250 }
251 }
252 } else {
253 echo $this->showSimpleMessage("Unable to get the code of the class {$controller}!", "error", "Creation", "warning circle", null, "msgControllers");
254 }
255 } else {
256 echo $this->showSimpleMessage("The action {$action} already exists in {$controller}!", "error", "Creation", "warning circle", null, "msgControllers");
257 }
258 }
259
260 private function generateRoutePath($path, $controllerName, $action, $parameters) {
261 if ($path == 1) {
262 $path = \str_replace('.', '/', $this->generateRouteName($controllerName, $action));
263 }
264 $params = CodeUtils::getParametersForRoute($parameters);
265 foreach ($params as $param) {
266 if ($param !== '{}' && \strpos($path, $param) === false) {
267 $path = \rtrim($path, '/') . '/' . $param;
268 }
269 }
270 return $path;
271 }
272
273 private function generateRouteName(string $controllerName, string $action) {
274 $ctrl = \str_ireplace('controller', '', $controllerName);
275 return \lcfirst($ctrl) . '.' . $action;
276 }
277
278 protected function generateRouteAnnotation($routeInfo, $controllerName, $action) {
279 if (\is_array($routeInfo)) {
280 $name = 'route';
281 $path = $routeInfo['path'];
282 $routeProperties['path'] = $path;
283 $strMethods = $routeInfo['methods'];
284 if (UString::isNotNull($strMethods)) {
285 $methods = \explode(',', $strMethods);
286 $methodsCount = \count($methods);
287 if ($methodsCount > 1) {
288 $routeProperties['methods'] = $methods;
289 } elseif ($methodsCount == 1) {
290 $name = \current($methods);
291 }
292 }
293 if (isset($routeInfo['ck-Cache'])) {
294 $routeProperties['cache'] = true;
295 if (isset($routeInfo['duration'])) {
296 $duration = $routeInfo['duration'];
297 if (\ctype_digit($duration)) {
298 $routeProperties['duration'] = $duration;
299 }
300 }
301 }
302 $routeProperties['name'] = $this->generateRouteName($controllerName, $action);
303
304 return CacheManager::getAnnotationsEngineInstance()->getAnnotation($this, $name, $routeProperties)->asAnnotation();
305 }
306 return '';
307 }
308
309 public function _createViewOp($controller, $action, $theme = null) {
310 $prefix = '';
311 if (! isset($theme) || $theme == '') {
312 $theme = $this->config['templateEngineOptions']['activeTheme'] ?? null;
313 }
314 if ($theme != null && DDDManager::getActiveDomain() != '') {
315 $prefix = 'themes/' . $theme . '/';
316 }
317 $viewFolder = DDDManager::getActiveViewFolder();
318 $viewName = $prefix . $controller . '/' . $action . ".html";
319 UFileSystem::safeMkdir($viewFolder . $prefix . $controller);
320 $templateDir = $this->getTemplateDir();
321 UFileSystem::openReplaceWriteFromTemplateFile($templateDir . 'view.tpl', $viewFolder . $viewName, [
322 '%controllerName%' => $controller,
323 '%actionName%' => $action
324 ]);
325 return DDDManager::getViewNamespace() . $viewName;
326 }
327
328 public function createAuthCrudView($frameworkName, $controllerName, $newName, $useViewInheritance) {
329 $folder = DDDManager::getActiveViewFolder() . $controllerName;
330 UFileSystem::safeMkdir($folder);
331 try {
332 $teInstance = Startup::getTemplateEngineInstance();
333 if (isset($teInstance)) {
334 if ($useViewInheritance) {
335 $blocks = $teInstance->getBlockNames($frameworkName);
336 if (count($blocks) > 0) {
337 $content = [
338 "{% extends \"" . $frameworkName . "\" %}\n"
339 ];
340 foreach ($blocks as $blockname) {
341 $content[] = "{% block " . $blockname . " %}\n\t{{ parent() }}\n{% endblock %}\n";
342 }
343 } else {
344 $content = [
345 $teInstance->getCode($frameworkName)
346 ];
347 }
348 } else {
349 $content = [
350 $teInstance->getCode($frameworkName)
351 ];
352 }
353 }
354 } catch (\Exception $e) {
355 $content = [
356 $teInstance->getCode($frameworkName)
357 ];
358 }
359 if (isset($content)) {
360 $strContent=\implode('', $content);
361 return UFileSystem::save($folder . \DS . $newName . '.html', $strContent);
362 }
363 }
364
365 public function setConfig($config) {
366 $this->config = $config;
367 }
368
373 public function setActiveDb($activeDb): void {
374 $this->activeDb = $activeDb;
375 }
376
381 public function getActiveDb(): string {
382 return $this->activeDb;
383 }
384}
Manager for caches (Router, Rest, models).
Manipulates class and namespace names Ubiquity\cache$ClassUtils This class is part of Ubiquity.
Starts the framework.
Definition Startup.php:19
Manager for a Domain Driven Design approach.
Ubiquity\utils\base$CodeUtils This class is part of Ubiquity.
Definition CodeUtils.php:13
File system utilities Ubiquity\utils\base$UFileSystem This class is part of Ubiquity.
Ubiquity\utils\base$UIntrospection This class is part of Ubiquity.
String utilities.
Definition UString.php:15