PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Controller/Scaffold.php

https://gitlab.com/nghiep5890/bakery
PHP | 451 lines | 265 code | 42 blank | 144 comment | 36 complexity | 46b1a0cf45f9c3d369ba63a8dc128f71 MD5 | raw file
  1. <?php
  2. /**
  3. * Scaffold.
  4. *
  5. * Automatic forms and actions generation for rapid web application development.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Controller
  17. * @since Cake v 0.10.0.1076
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. /**
  21. * Scaffolding is a set of automatic actions for starting web development work faster.
  22. *
  23. * Scaffold inspects your database tables, and making educated guesses, sets up a
  24. * number of pages for each of your Models. These pages have data forms that work,
  25. * and afford the web developer an early look at the data, and the possibility to over-ride
  26. * scaffolded actions with custom-made ones.
  27. *
  28. * @package Cake.Controller
  29. * @deprecated 3.0.0 Dynamic scaffolding will be removed and replaced in 3.0
  30. */
  31. class Scaffold {
  32. /**
  33. * Controller object
  34. *
  35. * @var Controller
  36. */
  37. public $controller = null;
  38. /**
  39. * Name of the controller to scaffold
  40. *
  41. * @var string
  42. */
  43. public $name = null;
  44. /**
  45. * Name of current model this view context is attached to
  46. *
  47. * @var string
  48. */
  49. public $model = null;
  50. /**
  51. * Path to View.
  52. *
  53. * @var string
  54. */
  55. public $viewPath;
  56. /**
  57. * Name of layout to use with this View.
  58. *
  59. * @var string
  60. */
  61. public $layout = 'default';
  62. /**
  63. * Request object
  64. *
  65. * @var CakeRequest
  66. */
  67. public $request;
  68. /**
  69. * Valid session.
  70. *
  71. * @var bool
  72. */
  73. protected $_validSession = null;
  74. /**
  75. * List of variables to collect from the associated controller
  76. *
  77. * @var array
  78. */
  79. protected $_passedVars = array(
  80. 'layout', 'name', 'viewPath', 'request'
  81. );
  82. /**
  83. * Title HTML element for current scaffolded view
  84. *
  85. * @var string
  86. */
  87. public $scaffoldTitle = null;
  88. /**
  89. * Construct and set up given controller with given parameters.
  90. *
  91. * @param Controller $controller Controller to scaffold
  92. * @param CakeRequest $request Request parameters.
  93. * @throws MissingModelException
  94. */
  95. public function __construct(Controller $controller, CakeRequest $request) {
  96. $this->controller = $controller;
  97. $count = count($this->_passedVars);
  98. for ($j = 0; $j < $count; $j++) {
  99. $var = $this->_passedVars[$j];
  100. $this->{$var} = $controller->{$var};
  101. }
  102. $this->redirect = array('action' => 'index');
  103. $this->modelClass = $controller->modelClass;
  104. $this->modelKey = $controller->modelKey;
  105. if (!is_object($this->controller->{$this->modelClass})) {
  106. throw new MissingModelException($this->modelClass);
  107. }
  108. $this->ScaffoldModel = $this->controller->{$this->modelClass};
  109. $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath));
  110. $this->scaffoldActions = $controller->scaffold;
  111. $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
  112. $modelClass = $this->controller->modelClass;
  113. $primaryKey = $this->ScaffoldModel->primaryKey;
  114. $displayField = $this->ScaffoldModel->displayField;
  115. $singularVar = Inflector::variable($modelClass);
  116. $pluralVar = Inflector::variable($this->controller->name);
  117. $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
  118. $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
  119. $scaffoldFields = array_keys($this->ScaffoldModel->schema());
  120. $associations = $this->_associations();
  121. $this->controller->set(compact(
  122. 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  123. 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'
  124. ));
  125. $this->controller->set('title_for_layout', $title);
  126. if ($this->controller->viewClass) {
  127. $this->controller->viewClass = 'Scaffold';
  128. }
  129. $this->_validSession = (
  130. isset($this->controller->Session) &&
  131. $this->controller->Session->valid() &&
  132. isset($this->controller->Flash)
  133. );
  134. $this->_scaffold($request);
  135. }
  136. /**
  137. * Renders a view action of scaffolded model.
  138. *
  139. * @param CakeRequest $request Request Object for scaffolding
  140. * @return mixed A rendered view of a row from Models database table
  141. * @throws NotFoundException
  142. */
  143. protected function _scaffoldView(CakeRequest $request) {
  144. if ($this->controller->beforeScaffold('view')) {
  145. if (isset($request->params['pass'][0])) {
  146. $this->ScaffoldModel->id = $request->params['pass'][0];
  147. }
  148. if (!$this->ScaffoldModel->exists()) {
  149. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  150. }
  151. $this->ScaffoldModel->recursive = 1;
  152. $this->controller->request->data = $this->ScaffoldModel->read();
  153. $this->controller->set(
  154. Inflector::variable($this->controller->modelClass), $this->request->data
  155. );
  156. $this->controller->render($this->request['action'], $this->layout);
  157. } elseif ($this->controller->scaffoldError('view') === false) {
  158. return $this->_scaffoldError();
  159. }
  160. }
  161. /**
  162. * Renders index action of scaffolded model.
  163. *
  164. * @param array $params Parameters for scaffolding
  165. * @return mixed A rendered view listing rows from Models database table
  166. */
  167. protected function _scaffoldIndex($params) {
  168. if ($this->controller->beforeScaffold('index')) {
  169. $this->ScaffoldModel->recursive = 0;
  170. $this->controller->set(
  171. Inflector::variable($this->controller->name), $this->controller->paginate()
  172. );
  173. $this->controller->render($this->request['action'], $this->layout);
  174. } elseif ($this->controller->scaffoldError('index') === false) {
  175. return $this->_scaffoldError();
  176. }
  177. }
  178. /**
  179. * Renders an add or edit action for scaffolded model.
  180. *
  181. * @param string $action Action (add or edit)
  182. * @return void
  183. */
  184. protected function _scaffoldForm($action = 'edit') {
  185. $this->controller->viewVars['scaffoldFields'] = array_merge(
  186. $this->controller->viewVars['scaffoldFields'],
  187. array_keys($this->ScaffoldModel->hasAndBelongsToMany)
  188. );
  189. $this->controller->render($action, $this->layout);
  190. }
  191. /**
  192. * Saves or updates the scaffolded model.
  193. *
  194. * @param CakeRequest $request Request Object for scaffolding
  195. * @param string $action add or edit
  196. * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
  197. * @throws NotFoundException
  198. */
  199. protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
  200. $formAction = 'edit';
  201. $success = __d('cake', 'updated');
  202. if ($action === 'add') {
  203. $formAction = 'add';
  204. $success = __d('cake', 'saved');
  205. }
  206. if ($this->controller->beforeScaffold($action)) {
  207. if ($action === 'edit') {
  208. if (isset($request->params['pass'][0])) {
  209. $this->ScaffoldModel->id = $request['pass'][0];
  210. }
  211. if (!$this->ScaffoldModel->exists()) {
  212. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  213. }
  214. }
  215. if (!empty($request->data)) {
  216. if ($action === 'create') {
  217. $this->ScaffoldModel->create();
  218. }
  219. if ($this->ScaffoldModel->save($request->data)) {
  220. if ($this->controller->afterScaffoldSave($action)) {
  221. $message = __d('cake',
  222. 'The %1$s has been %2$s',
  223. Inflector::humanize($this->modelKey),
  224. $success
  225. );
  226. return $this->_sendMessage($message, 'success');
  227. }
  228. return $this->controller->afterScaffoldSaveError($action);
  229. }
  230. if ($this->_validSession) {
  231. $this->controller->Flash->set(__d('cake', 'Please correct errors below.'));
  232. }
  233. }
  234. if (empty($request->data)) {
  235. if ($this->ScaffoldModel->id) {
  236. $this->controller->data = $request->data = $this->ScaffoldModel->read();
  237. } else {
  238. $this->controller->data = $request->data = $this->ScaffoldModel->create();
  239. }
  240. }
  241. foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
  242. $varName = Inflector::variable(Inflector::pluralize(
  243. preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
  244. ));
  245. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  246. }
  247. foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
  248. $varName = Inflector::variable(Inflector::pluralize($assocName));
  249. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  250. }
  251. return $this->_scaffoldForm($formAction);
  252. } elseif ($this->controller->scaffoldError($action) === false) {
  253. return $this->_scaffoldError();
  254. }
  255. }
  256. /**
  257. * Performs a delete on given scaffolded Model.
  258. *
  259. * @param CakeRequest $request Request for scaffolding
  260. * @return mixed Success on delete, error if delete fails
  261. * @throws MethodNotAllowedException When HTTP method is not a DELETE
  262. * @throws NotFoundException When id being deleted does not exist.
  263. */
  264. protected function _scaffoldDelete(CakeRequest $request) {
  265. if ($this->controller->beforeScaffold('delete')) {
  266. if (!$request->is('post')) {
  267. throw new MethodNotAllowedException();
  268. }
  269. $id = false;
  270. if (isset($request->params['pass'][0])) {
  271. $id = $request->params['pass'][0];
  272. }
  273. $this->ScaffoldModel->id = $id;
  274. if (!$this->ScaffoldModel->exists()) {
  275. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
  276. }
  277. if ($this->ScaffoldModel->delete()) {
  278. $message = __d('cake', 'The %1$s with id: %2$s has been deleted.', Inflector::humanize($this->modelClass), $id);
  279. return $this->_sendMessage($message, 'success');
  280. }
  281. $message = __d('cake',
  282. 'There was an error deleting the %1$s with id: %2$s',
  283. Inflector::humanize($this->modelClass),
  284. $id
  285. );
  286. return $this->_sendMessage($message);
  287. } elseif ($this->controller->scaffoldError('delete') === false) {
  288. return $this->_scaffoldError();
  289. }
  290. }
  291. /**
  292. * Sends a message to the user. Either uses Sessions or flash messages depending
  293. * on the availability of a session
  294. *
  295. * @param string $message Message to display
  296. * @param string $element Flash template to use
  297. * @return void
  298. */
  299. protected function _sendMessage($message, $element = 'default') {
  300. if ($this->_validSession) {
  301. $this->controller->Flash->set($message, compact('element'));
  302. return $this->controller->redirect($this->redirect);
  303. }
  304. $this->controller->flash($message, $this->redirect);
  305. }
  306. /**
  307. * Show a scaffold error
  308. *
  309. * @return mixed A rendered view showing the error
  310. */
  311. protected function _scaffoldError() {
  312. return $this->controller->render('error', $this->layout);
  313. }
  314. /**
  315. * When methods are now present in a controller
  316. * scaffoldView is used to call default Scaffold methods if:
  317. * `public $scaffold;` is placed in the controller's class definition.
  318. *
  319. * @param CakeRequest $request Request object for scaffolding
  320. * @return void
  321. * @throws MissingActionException When methods are not scaffolded.
  322. * @throws MissingDatabaseException When the database connection is undefined.
  323. */
  324. protected function _scaffold(CakeRequest $request) {
  325. $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
  326. $prefixes = Configure::read('Routing.prefixes');
  327. $scaffoldPrefix = $this->scaffoldActions;
  328. if (isset($db)) {
  329. if (empty($this->scaffoldActions)) {
  330. $this->scaffoldActions = array(
  331. 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete'
  332. );
  333. } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) {
  334. $this->scaffoldActions = array(
  335. $scaffoldPrefix . '_index',
  336. $scaffoldPrefix . '_list',
  337. $scaffoldPrefix . '_view',
  338. $scaffoldPrefix . '_add',
  339. $scaffoldPrefix . '_create',
  340. $scaffoldPrefix . '_edit',
  341. $scaffoldPrefix . '_update',
  342. $scaffoldPrefix . '_delete'
  343. );
  344. }
  345. if (in_array($request->params['action'], $this->scaffoldActions)) {
  346. if (!empty($prefixes)) {
  347. $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']);
  348. }
  349. switch ($request->params['action']) {
  350. case 'index':
  351. case 'list':
  352. $this->_scaffoldIndex($request);
  353. break;
  354. case 'view':
  355. $this->_scaffoldView($request);
  356. break;
  357. case 'add':
  358. case 'create':
  359. $this->_scaffoldSave($request, 'add');
  360. break;
  361. case 'edit':
  362. case 'update':
  363. $this->_scaffoldSave($request, 'edit');
  364. break;
  365. case 'delete':
  366. $this->_scaffoldDelete($request);
  367. break;
  368. }
  369. } else {
  370. throw new MissingActionException(array(
  371. 'controller' => get_class($this->controller),
  372. 'action' => $request->action
  373. ));
  374. }
  375. } else {
  376. throw new MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig));
  377. }
  378. }
  379. /**
  380. * Returns associations for controllers models.
  381. *
  382. * @return array Associations for model
  383. */
  384. protected function _associations() {
  385. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  386. $associations = array();
  387. foreach ($keys as $type) {
  388. foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
  389. $associations[$type][$assocKey]['primaryKey'] =
  390. $this->ScaffoldModel->{$assocKey}->primaryKey;
  391. $associations[$type][$assocKey]['displayField'] =
  392. $this->ScaffoldModel->{$assocKey}->displayField;
  393. $associations[$type][$assocKey]['foreignKey'] =
  394. $assocData['foreignKey'];
  395. list($plugin, $model) = pluginSplit($assocData['className']);
  396. if ($plugin) {
  397. $plugin = Inflector::underscore($plugin);
  398. }
  399. $associations[$type][$assocKey]['plugin'] = $plugin;
  400. $associations[$type][$assocKey]['controller'] =
  401. Inflector::pluralize(Inflector::underscore($model));
  402. if ($type === 'hasAndBelongsToMany') {
  403. $associations[$type][$assocKey]['with'] = $assocData['with'];
  404. }
  405. }
  406. }
  407. return $associations;
  408. }
  409. }