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