Scaffold.php 14 KB

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