Passed
Push — master ( a6b5c0...1b00af )
by Jean-Christophe
05:56
created

ScaffoldController::addRestController()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
crap 1
1
<?php
2
3
namespace Ubiquity\scaffolding;
4
5
use Ubiquity\controllers\Startup;
6
use Ubiquity\utils\base\UFileSystem;
7
use Ubiquity\utils\base\UString;
8
use Ubiquity\controllers\admin\utils\CodeUtils;
9
use Ubiquity\utils\base\UIntrospection;
10
use Ubiquity\cache\ClassUtils;
11
use Ubiquity\scaffolding\creators\AuthControllerCreator;
12
use Ubiquity\scaffolding\creators\CrudControllerCreator;
13
use Ubiquity\scaffolding\creators\RestControllerCreator;
14
use Ubiquity\scaffolding\creators\RestApiControllerCreator;
15
16
/**
17
 * Base class for Scaffolding.
18
 * Ubiquity\scaffolding$ScaffoldController
19
 * This class is part of Ubiquity
20
 *
21
 * @author jcheron <[email protected]>
22
 * @version 1.0.3
23
 *
24
 */
25
abstract class ScaffoldController {
26
	public static $views = [
27
							"CRUD" => [ "index" => "@framework/crud/index.html","form" => "@framework/crud/form.html","display" => "@framework/crud/display.html" ],
28
							"auth" => [ "index" => "@framework/auth/index.html","info" => "@framework/auth/info.html","noAccess" => "@framework/auth/noAccess.html","disconnected" => "@framework/auth/disconnected.html","message" => "@framework/auth/message.html","baseTemplate" => "@framework/auth/baseTemplate.html" ] ];
29
30
	public abstract function getTemplateDir();
31
32
	public function _refreshRest($refresh = false) {
33
	}
34
35
	public function initRestCache($refresh = true) {
36
	}
37
38
	protected abstract function storeControllerNameInSession($controller);
39
40
	public abstract function showSimpleMessage($content, $type, $title = null, $icon = "info", $timeout = NULL, $staticName = null);
41
42
	protected abstract function _addMessageForRouteCreation($path, $jsCallback = "");
43
44 2
	public function _createMethod($access, $name, $parameters = "", $return = "", $content = "", $comment = "") {
45 2
		$templateDir = $this->getTemplateDir ();
46 2
		$keyAndValues = [ "%access%" => $access,"%name%" => $name,"%parameters%" => $parameters,"%content%" => $content,"%comment%" => $comment,"%return%" => $return ];
47 2
		return UFileSystem::openReplaceInTemplateFile ( $templateDir . "method.tpl", $keyAndValues );
48
	}
49
50 5
	public function _createController($controllerName, $variables = [], $ctrlTemplate = 'controller.tpl', $hasView = false, $jsCallback = "") {
51 5
		$message = "";
52 5
		$templateDir = $this->getTemplateDir ();
53 5
		$controllersNS = \rtrim ( Startup::getNS ( "controllers" ), "\\" );
54 5
		$controllersDir = \ROOT . \DS . str_replace ( "\\", \DS, $controllersNS );
55 5
		$controllerName = \ucfirst ( $controllerName );
56 5
		$filename = $controllersDir . \DS . $controllerName . ".php";
57 5
		if (\file_exists ( $filename ) === false) {
58 5
			$namespace = "";
59 5
			if ($controllersNS !== "") {
60 5
				$namespace = "namespace " . $controllersNS . ";";
61
			}
62 5
			$msgView = "";
63 5
			$indexContent = "";
64 5
			if ($hasView) {
65 1
				$viewDir = \ROOT . \DS . "views" . \DS . $controllerName . \DS;
66 1
				UFileSystem::safeMkdir ( $viewDir );
67 1
				$viewName = $viewDir . \DS . "index.html";
68 1
				UFileSystem::openReplaceWriteFromTemplateFile ( $templateDir . "view.tpl", $viewName, [ "%controllerName%" => $controllerName,"%actionName%" => "index" ] );
69 1
				$msgView = "<br>The default view associated has been created in <b>" . UFileSystem::cleanPathname ( \ROOT . \DS . $viewDir ) . "</b>";
70 1
				$indexContent = "\$this->loadView(\"" . $controllerName . "/index.html\");";
71
			}
72 5
			$variables = \array_merge ( $variables, [ "%controllerName%" => $controllerName,"%indexContent%" => $indexContent,"%namespace%" => $namespace ] );
73 5
			UFileSystem::openReplaceWriteFromTemplateFile ( $templateDir . $ctrlTemplate, $filename, $variables );
74 5
			$msgContent = "The <b>" . $controllerName . "</b> controller has been created in <b>" . UFileSystem::cleanFilePathname ( $filename ) . "</b>." . $msgView;
75 5
			if (isset ( $variables ["%path%"] ) && $variables ["%path%"] !== "") {
76
				$msgContent .= $this->_addMessageForRouteCreation ( $variables ["%path%"], $jsCallback );
77
			}
78 5
			$this->storeControllerNameInSession ( $controllersNS . "\\" . $controllerName );
79 5
			$message = $this->showSimpleMessage ( $msgContent, "success", null, "checkmark circle", NULL, "msgGlobal" );
80
		} else {
81
			$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" );
82
		}
83 5
		return $message;
84
	}
85
86 1
	public function addCrudController($crudControllerName, $resource, $crudDatas = null, $crudViewer = null, $crudEvents = null, $crudViews = null, $routePath = '') {
87 1
		$crudController = new CrudControllerCreator ( $crudControllerName, $resource, $crudDatas, $crudViewer, $crudEvents, $crudViews, $routePath );
88 1
		$crudController->create ( $this );
89 1
	}
90
91 1
	public function addAuthController($authControllerName, $baseClass, $authViews = null, $routePath = "") {
92 1
		$authCreator = new AuthControllerCreator ( $authControllerName, $baseClass, $authViews, $routePath );
93 1
		$authCreator->create ( $this );
94 1
	}
95
96 1
	public function addRestController($restControllerName, $resource, $routePath = "", $reInit = true) {
97 1
		$restCreator = new RestControllerCreator ( $restControllerName, $resource, $routePath );
98 1
		$restCreator->create ( $this, $reInit );
99 1
	}
100
101
	public function addRestApiController($restControllerName, $routePath = "", $reInit = true) {
102
		$restCreator = new RestApiControllerCreator ( $restControllerName, $routePath );
103
		$restCreator->create ( $this, $reInit );
104
	}
105
106 2
	public function _createClass($template, $classname, $namespace, $uses, $extendsOrImplements, $classContent) {
107 2
		$namespaceVar = "";
108 2
		if (UString::isNotNull ( $namespace )) {
109 2
			$namespaceVar = "namespace {$namespace};";
110
		}
111 2
		$variables = [ "%classname%" => $classname,"%namespace%" => $namespaceVar,"%uses%" => $uses,"%extendsOrImplements%" => $extendsOrImplements,"%classContent%" => $classContent ];
112 2
		$templateDir = $this->getTemplateDir ();
113 2
		$directory = UFileSystem::getDirFromNamespace ( $namespace );
114 2
		UFileSystem::safeMkdir ( $directory );
115 2
		$filename = UFileSystem::cleanFilePathname ( $directory . \DS . $classname . ".php" );
116 2
		if (! file_exists ( $filename )) {
117 2
			UFileSystem::openReplaceWriteFromTemplateFile ( $templateDir . $template, $filename, $variables );
118 2
			$message = $this->showSimpleMessage ( "The <b>" . $classname . "</b> class has been created in <b>" . $filename . "</b>.", "success", "Creation", "checkmark circle" );
119
		} else {
120
			$message = $this->showSimpleMessage ( "The file <b>" . $filename . "</b> already exists.<br>Can not create the <b>" . $classname . "</b> class!", "warning", "Creation", "warning circle" );
121
		}
122 2
		return $message;
123
	}
124
125 1
	public function _newAction($controller, $action, $parameters = null, $content = '', $routeInfo = null, $createView = false) {
126 1
		$templateDir = $this->getTemplateDir ();
127 1
		$msgContent = "";
128 1
		$r = new \ReflectionClass ( $controller );
129 1
		if (! method_exists ( $controller, $action )) {
130 1
			$ctrlFilename = $r->getFileName ();
131 1
			$content = CodeUtils::indent ( $content, 2 );
132 1
			$classCode = UIntrospection::getClassCode ( $controller );
133 1
			if ($classCode !== false) {
134 1
				$fileContent = \implode ( "", $classCode );
135 1
				$fileContent = \trim ( $fileContent );
136 1
				$posLast = \strrpos ( $fileContent, "}" );
137 1
				if ($posLast !== false) {
138 1
					if ($createView) {
139 1
						$viewname = $this->_createViewOp ( ClassUtils::getClassSimpleName ( $controller ), $action );
140 1
						$content .= "\n\t\t\$this->loadView('" . $viewname . "');\n";
141 1
						$msgContent .= "<br>Created view : <b>" . $viewname . "</b>";
142
					}
143 1
					$routeAnnotation = "";
144 1
					if (is_array ( $routeInfo )) {
145 1
						$name = "route";
146 1
						$path = $routeInfo ["path"];
147 1
						$routeProperties = [ '"' . $path . '"' ];
148 1
						$methods = $routeInfo ["methods"];
149 1
						if (UString::isNotNull ( $methods )) {
150
							$routeProperties [] = '"methods"=>' . $this->getMethods ( $methods );
151
						}
152 1
						if (isset ( $routeInfo ["ck-Cache"] )) {
153
							$routeProperties [] = '"cache"=>true';
154
							if (isset ( $routeInfo ["duration"] )) {
155
								$duration = $routeInfo ["duration"];
156
								if (\ctype_digit ( $duration )) {
157
									$routeProperties [] = '"duration"=>' . $duration;
158
								}
159
							}
160
						}
161 1
						$routeProperties = \implode ( ",", $routeProperties );
162 1
						$routeAnnotation = UFileSystem::openReplaceInTemplateFile ( $templateDir . "annotation.tpl", [ "%name%" => $name,"%properties%" => $routeProperties ] );
163
164 1
						$msgContent .= $this->_addMessageForRouteCreation ( $path );
165
					}
166 1
					$parameters = CodeUtils::cleanParameters ( $parameters );
167 1
					$actionContent = UFileSystem::openReplaceInTemplateFile ( $templateDir . "action.tpl", [ "%route%" => "\n" . $routeAnnotation ?? '',"%actionName%" => $action,"%parameters%" => $parameters,"%content%" => $content ] );
168 1
					$fileContent = \substr_replace ( $fileContent, "\n%content%", $posLast - 1, 0 );
169 1
					if (! CodeUtils::isValidCode ( '<?php ' . $content )) {
170
						echo $this->showSimpleMessage ( "Errors parsing action content!", "warning", "Creation", "warning circle", null, "msgControllers" );
171
						return;
172
					} else {
173 1
						if (UFileSystem::replaceWriteFromContent ( $fileContent . "\n", $ctrlFilename, [ '%content%' => $actionContent ] )) {
174 1
							$msgContent = "The action <b>{$action}</b> is created in controller <b>{$controller}</b>" . $msgContent;
175 1
							echo $this->showSimpleMessage ( $msgContent, "info", "Creation", "info circle", null, "msgControllers" );
176
						}
177
					}
178
				}
179
			} else {
180
				echo $this->showSimpleMessage ( "The action {$action} already exists in {$controller}!", "error", "Creation", "warning circle", null, "msgControllers" );
181
			}
182
		}
183 1
	}
184
185
	protected function getMethods($strMethods) {
186
		$methods = \explode ( ",", $strMethods );
187
		$result = [ ];
188
		foreach ( $methods as $method ) {
189
			$result [] = '"' . $method . '"';
190
		}
191
		return "[" . \implode ( ",", $result ) . "]";
192
	}
193
194 1
	protected function _createViewOp($controller, $action) {
195 1
		$viewName = $controller . "/" . $action . ".html";
196 1
		UFileSystem::safeMkdir ( \ROOT . \DS . "views" . \DS . $controller );
197 1
		$templateDir = $this->getTemplateDir ();
198 1
		UFileSystem::openReplaceWriteFromTemplateFile ( $templateDir . "view.tpl", \ROOT . \DS . "views" . \DS . $viewName, [ "%controllerName%" => $controller,"%actionName%" => $action ] );
199 1
		return $viewName;
200
	}
201
202 2
	public function createAuthCrudView($frameworkName, $controllerName, $newName) {
203 2
		$folder = \ROOT . \DS . "views" . \DS . $controllerName;
204 2
		UFileSystem::safeMkdir ( $folder );
205
		try {
206 2
			$teInstance = Startup::getTempateEngineInstance ();
207 2
			if (isset ( $teInstance )) {
208 2
				$blocks = $teInstance->getBlockNames ( $frameworkName );
209 2
				if (sizeof ( $blocks ) > 0) {
210 2
					$content = [ "{% extends \"" . $frameworkName . "\" %}\n" ];
211 2
					foreach ( $blocks as $blockname ) {
212 2
						$content [] = "{% block " . $blockname . " %}\n\t{{ parent() }}\n{% endblock %}\n";
213
					}
214
				} else {
215 2
					$content = [ $teInstance->getCode ( $frameworkName ) ];
216
				}
217
			}
218 1
		} catch ( \Exception $e ) {
219 1
			$content = [ $teInstance->getCode ( $frameworkName ) ];
220
		}
221 2
		if (isset ( $content )) {
222 2
			return UFileSystem::save ( $folder . \DS . $newName . ".html", implode ( "", $content ) );
223
		}
224
	}
225
}
226
227