Scaffold.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 http://www.opensource.org/licenses/mit-license.php MIT License
  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. }
  228. return $this->controller->afterScaffoldSaveError($action);
  229. }
  230. if ($this->_validSession) {
  231. $this->controller->Session->setFlash(__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);
  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. * @return void
  297. */
  298. protected function _sendMessage($message) {
  299. if ($this->_validSession) {
  300. $this->controller->Session->setFlash($message);
  301. $this->controller->redirect($this->redirect);
  302. } else {
  303. $this->controller->flash($message, $this->redirect);
  304. }
  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' => $this->controller->name,
  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. }