PageRenderTime 55ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/ahmadfatoni/apigenerator/controllers/ApiGeneratorController.php

https://bitbucket.org/walshd/server-healthapp-cms
PHP | 336 lines | 210 code | 92 blank | 34 comment | 34 complexity | 2d6556bf381c79b1ab34f87f597ab395 MD5 | raw file
Possible License(s): GPL-2.0, MIT
  1. <?php namespace AhmadFatoni\ApiGenerator\Controllers;
  2. use Backend\Classes\Controller;
  3. use AhmadFatoni\ApiGenerator\Models\ApiGenerator;
  4. use BackendMenu;
  5. use Backend;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Filesystem\Filesystem;
  8. use Redirect;
  9. use Flash;
  10. class ApiGeneratorController extends Controller
  11. {
  12. public $implement = ['Backend\Behaviors\ListController','Backend\Behaviors\FormController','Backend\Behaviors\ReorderController'];
  13. public $listConfig = 'config_list.yaml';
  14. public $formConfig = 'config_form.yaml';
  15. public $reorderConfig = 'config_reorder.yaml';
  16. protected $path = "/api/";
  17. private $homePage = 'ahmadfatoni/apigenerator/apigeneratorcontroller';
  18. protected $files;
  19. public function __construct(Filesystem $files)
  20. {
  21. parent::__construct();
  22. BackendMenu::setContext('AhmadFatoni.ApiGenerator', 'api-generator');
  23. $this->files = $files;
  24. }
  25. /**
  26. * delete selected data (multiple delete)
  27. * @return [type] [description]
  28. */
  29. public function index_onDelete()
  30. {
  31. if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {
  32. foreach ($checkedIds as $id) {
  33. if ((!$item = ApiGenerator::find($id)))
  34. continue;
  35. $name = $item->name;
  36. if($item->delete()){
  37. $this->deleteApi($name);
  38. }
  39. }
  40. Flash::success('Successfully deleted those data.');
  41. }
  42. return $this->listRefresh();
  43. }
  44. /**
  45. * generate API
  46. * @param Request $request [description]
  47. * @return [type] [description]
  48. */
  49. public function generateApi(Request $request){
  50. $data['model'] = $request->model;
  51. $modelname = explode("\\", $request->model);
  52. $modelname = $modelname[count($modelname)-1];
  53. $data['modelname'] = $modelname;
  54. $data['controllername'] = str_replace(" ", "", $request->name);
  55. $data['endpoint'] = $request->endpoint;
  56. $data['custom_format'] = $request->custom_format;
  57. if( strpos($data['controllername'], ".") OR strpos($data['controllername'], "/") ){
  58. Flash::success('Failed to create data, invalid API name.');
  59. return Redirect::to( Backend::url($this->homePage));
  60. }
  61. if( isset($request->id) ){
  62. $this->deleteApi($request->oldname, 'false');
  63. }
  64. $this->files->put(__DIR__ . $this->path . $data['controllername'].'Controller.php', $this->compile($data));
  65. $this->files->put(__DIR__ . '/'.'../routes.php', $this->compileRoute($data));
  66. return Redirect::to( Backend::url($this->homePage));
  67. }
  68. /**
  69. * delete available API
  70. * @param [type] $name [description]
  71. * @param [type] $redirect [description]
  72. * @return [type] [description]
  73. */
  74. public function deleteApi($name, $redirect = null){
  75. $fileLocation = __DIR__ . $this->path.$name;
  76. $fileLocation = str_replace(".", "", $fileLocation);
  77. if( ! file_exists($fileLocation.'Controller.php') ){
  78. Flash::success('Failed to delete data, invalid file location.');
  79. return Redirect::to( Backend::url($this->homePage));
  80. }
  81. if( strpos( strtolower($name), 'apigenerator' ) === false){
  82. $data = [];
  83. //generate new route
  84. $this->files->put(__DIR__ . '/'.'../routes.php', $this->compileRoute($data));
  85. //remove controller
  86. if (file_exists( __DIR__ . $this->path.$name.'Controller.php' )) {
  87. unlink(__DIR__ . $this->path.$name.'Controller.php');
  88. }
  89. if( $redirect != null ){
  90. return 'success without redirect';
  91. }
  92. }
  93. return Redirect::to( Backend::url($this->homePage));
  94. }
  95. public function updateApi($name){
  96. }
  97. /**
  98. * compile controller from template
  99. * @param [type] $data [description]
  100. * @return [type] [description]
  101. */
  102. public function compile($data){
  103. if( $data['custom_format'] != ''){
  104. $template = $this->files->get(__DIR__ .'/../template/customcontroller.dot');
  105. $template = $this->replaceAttribute($template, $data);
  106. $template = $this->replaceCustomAttribute($template, $data);
  107. }else{
  108. $template = $this->files->get(__DIR__ .'/../template/controller.dot');
  109. $template = $this->replaceAttribute($template, $data);
  110. }
  111. return $template;
  112. }
  113. /**
  114. * replace attribute
  115. * @param [type] $template [description]
  116. * @param [type] $data [description]
  117. * @return [type] [description]
  118. */
  119. public function replaceAttribute($template, $data){
  120. if( isset( $data['model'] ) ){
  121. $template = str_replace('{{model}}', $data['model'], $template);
  122. }
  123. $template = str_replace('{{modelname}}', $data['modelname'], $template);
  124. $template = str_replace('{{controllername}}', $data['controllername'], $template);
  125. return $template;
  126. }
  127. /**
  128. * replace custom attribute
  129. * @param [type] $template [description]
  130. * @param [type] $data [description]
  131. * @return [type] [description]
  132. */
  133. public function replaceCustomAttribute($template, $data){
  134. $arr = str_replace('\t', '', $data['custom_format']);
  135. $arr = json_decode($arr);
  136. $select = str_replace('<br />', '', $this->compileOpenIndexFunction($data['modelname'], 'index'));
  137. $show = str_replace('<br />', '', $this->compileOpenIndexFunction($data['modelname'], 'show'));
  138. $fillableParent = '';
  139. if( isset($arr->fillable) AND $arr->fillable != null ) {
  140. $fillableParent = $this->compileFillableParent($arr->fillable);
  141. }
  142. if( isset($arr->relation) AND $arr->relation != null AND is_array($arr->relation) AND count($arr->relation) > 0) {
  143. $select .= str_replace('<br />', '', $this->compileFillableChild($arr->relation));
  144. $show .= str_replace('<br />', '', $this->compileFillableChild($arr->relation));
  145. }
  146. $select .= "->select(".$fillableParent.")";
  147. $show .= "->select(".$fillableParent.")->where('id', '=', \$id)->first();";
  148. ( $fillableParent != '') ? $select .= "->get()->toArray();" : $select .= "->toArray();" ;
  149. $closeFunction = str_replace('<br />', '', nl2br(
  150. "
  151. return \$this->helpers->apiArrayResponseBuilder(200, 'success', \$data);
  152. }"));
  153. $select .= $closeFunction;
  154. $show .= $closeFunction;
  155. $template = str_replace('{{select}}', $select, $template);
  156. $template = str_replace('{{show}}', $show, $template);
  157. return $template;
  158. }
  159. public function compileOpenIndexFunction($modelname, $type){
  160. if( $type == 'index'){
  161. return nl2br("
  162. public function index(){
  163. \$data = \$this->".$modelname);
  164. }else{
  165. return nl2br("
  166. public function show(\$id){
  167. \$data = \$this->".$modelname);
  168. }
  169. }
  170. public function compileFillableParent($fillable){
  171. $fillableParentArr = explode(",", $fillable);
  172. $fillableParent = '';
  173. foreach ($fillableParentArr as $key) {
  174. $fillableParent .= ",'".$key."'";
  175. }
  176. $fillableParent = substr_replace($fillableParent, '', 0 , 1);
  177. return $fillableParent;
  178. }
  179. public function compileFillableChild($fillable){
  180. $select = "->with(array(";
  181. foreach ($fillable as $key) {
  182. $fillableChild = "";
  183. if( isset($key->fillable) AND $key->fillable != null ){
  184. $fillableChildArr = explode(",", $key->fillable);
  185. foreach ($fillableChildArr as $key2) {
  186. $fillableChild .= ",'".$key2."'";
  187. }
  188. $fillableChild = substr_replace($fillableChild, '', 0 , 1);
  189. }
  190. $select .= nl2br(
  191. "
  192. '".$key->name."'=>function(\$query){
  193. \$query->select(".$fillableChild.");
  194. },");
  195. }
  196. $select .= " ))";
  197. return $select;
  198. }
  199. public function compileRoute($data){
  200. $oldData = ApiGenerator::all();
  201. $routeList = "";
  202. if( count($oldData) > 0 ){
  203. $routeList .= $this->parseRouteOldData($oldData, $data);
  204. }
  205. if( count($data) > 0 ){
  206. $data['modelname'] = $data['endpoint'];
  207. if( $data['modelname'][0] == "/" ){
  208. $data['modelname'] = substr_replace($data['modelname'], '', 0 , 1);
  209. }
  210. $routeList .= $this->parseRoute($data);
  211. }
  212. $route = $this->files->get(__DIR__ .'/../template/routes.dot');
  213. $route = str_replace('{{route}}', $routeList, $route);
  214. return $route;
  215. }
  216. public function parseRouteOldData($oldData, $data = null){
  217. $routeList = "";
  218. if( count($data) == 0 ) $data['modelname']='';
  219. foreach ( $oldData as $key ) {
  220. $modelname = explode("\\", $key->model);
  221. $modelname = $modelname[count($modelname)-1];
  222. $old['modelname'] = $key->name;
  223. $old['controllername'] = $key->name;
  224. if( $data['modelname'] != $modelname ){
  225. if( $old['modelname'][0] == "/" ){
  226. $old['modelname'] = substr_replace($old['modelname'], '', 0 , 1);
  227. }
  228. $routeList .= $this->parseRoute($old);
  229. }
  230. }
  231. return $routeList;
  232. }
  233. public function parseRoute($data){
  234. $template = $this->files->get(__DIR__ .'/../template/route.dot');
  235. $template = $this->replaceAttribute($template, $data);
  236. return $template;
  237. }
  238. public static function getAfterFilters() {return [];}
  239. public static function getBeforeFilters() {return [];}
  240. public static function getMiddleware() {return [];}
  241. public function callAction($method, $parameters=false) {
  242. return call_user_func_array(array($this, $method), $parameters);
  243. }
  244. }