Scaffold.php 13 KB

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