PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/testXML/lib/Cake/Controller/Scaffold.php

https://bitbucket.org/allanxyh/project
PHP | 453 lines | 268 code | 42 blank | 143 comment | 45 complexity | a19e786ce792a1d5a681690f77ac7a5d MD5 | raw file
  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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Controller
  18. * @since Cake v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('Scaffold', 'View');
  22. /**
  23. * Scaffolding is a set of automatic actions for starting web development work faster.
  24. *
  25. * Scaffold inspects your database tables, and making educated guesses, sets up a
  26. * number of pages for each of your Models. These pages have data forms that work,
  27. * and afford the web developer an early look at the data, and the possibility to over-ride
  28. * scaffolded actions with custom-made ones.
  29. *
  30. * @package Cake.Controller
  31. */
  32. class Scaffold {
  33. /**
  34. * Controller object
  35. *
  36. * @var Controller
  37. */
  38. public $controller = null;
  39. /**
  40. * Name of the controller to scaffold
  41. *
  42. * @var string
  43. */
  44. public $name = null;
  45. /**
  46. * Name of current model this view context is attached to
  47. *
  48. * @var string
  49. */
  50. public $model = null;
  51. /**
  52. * Path to View.
  53. *
  54. * @var string
  55. */
  56. public $viewPath;
  57. /**
  58. * Name of layout to use with this View.
  59. *
  60. * @var string
  61. */
  62. public $layout = 'default';
  63. /**
  64. * Request object
  65. *
  66. * @var CakeRequest
  67. */
  68. public $request;
  69. /**
  70. * Valid session.
  71. *
  72. * @var boolean
  73. */
  74. protected $_validSession = null;
  75. /**
  76. * List of variables to collect from the associated controller
  77. *
  78. * @var array
  79. */
  80. protected $_passedVars = array(
  81. 'layout', 'name', 'viewPath', 'request'
  82. );
  83. /**
  84. * Title HTML element for current scaffolded view
  85. *
  86. * @var string
  87. */
  88. public $scaffoldTitle = null;
  89. /**
  90. * Construct and set up given controller with given parameters.
  91. *
  92. * @param Controller $controller Controller to scaffold
  93. * @param CakeRequest $request Request parameters.
  94. * @throws MissingModelException
  95. */
  96. public function __construct(Controller $controller, CakeRequest $request) {
  97. $this->controller = $controller;
  98. $count = count($this->_passedVars);
  99. for ($j = 0; $j < $count; $j++) {
  100. $var = $this->_passedVars[$j];
  101. $this->{$var} = $controller->{$var};
  102. }
  103. $this->redirect = array('action' => 'index');
  104. $this->modelClass = $controller->modelClass;
  105. $this->modelKey = $controller->modelKey;
  106. if (!is_object($this->controller->{$this->modelClass})) {
  107. throw new MissingModelException($this->modelClass);
  108. }
  109. $this->ScaffoldModel = $this->controller->{$this->modelClass};
  110. $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath));
  111. $this->scaffoldActions = $controller->scaffold;
  112. $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
  113. $modelClass = $this->controller->modelClass;
  114. $primaryKey = $this->ScaffoldModel->primaryKey;
  115. $displayField = $this->ScaffoldModel->displayField;
  116. $singularVar = Inflector::variable($modelClass);
  117. $pluralVar = Inflector::variable($this->controller->name);
  118. $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
  119. $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
  120. $scaffoldFields = array_keys($this->ScaffoldModel->schema());
  121. $associations = $this->_associations();
  122. $this->controller->set(compact(
  123. 'title_for_layout', 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  124. 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'
  125. ));
  126. $this->controller->set('title_for_layout', $title);
  127. if ($this->controller->viewClass) {
  128. $this->controller->viewClass = 'Scaffold';
  129. }
  130. $this->_validSession = (
  131. isset($this->controller->Session) && $this->controller->Session->valid() != false
  132. );
  133. $this->_scaffold($request);
  134. }
  135. /**
  136. * Renders a view action of scaffolded model.
  137. *
  138. * @param CakeRequest $request Request Object for scaffolding
  139. * @return mixed A rendered view of a row from Models database table
  140. * @throws NotFoundException
  141. */
  142. protected function _scaffoldView(CakeRequest $request) {
  143. if ($this->controller->beforeScaffold('view')) {
  144. if (isset($request->params['pass'][0])) {
  145. $this->ScaffoldModel->id = $request->params['pass'][0];
  146. }
  147. if (!$this->ScaffoldModel->exists()) {
  148. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  149. }
  150. $this->ScaffoldModel->recursive = 1;
  151. $this->controller->request->data = $this->ScaffoldModel->read();
  152. $this->controller->set(
  153. Inflector::variable($this->controller->modelClass), $this->request->data
  154. );
  155. $this->controller->render($this->request['action'], $this->layout);
  156. } elseif ($this->controller->scaffoldError('view') === false) {
  157. return $this->_scaffoldError();
  158. }
  159. }
  160. /**
  161. * Renders index action of scaffolded model.
  162. *
  163. * @param array $params Parameters for scaffolding
  164. * @return mixed A rendered view listing rows from Models database table
  165. */
  166. protected function _scaffoldIndex($params) {
  167. if ($this->controller->beforeScaffold('index')) {
  168. $this->ScaffoldModel->recursive = 0;
  169. $this->controller->set(
  170. Inflector::variable($this->controller->name), $this->controller->paginate()
  171. );
  172. $this->controller->render($this->request['action'], $this->layout);
  173. } elseif ($this->controller->scaffoldError('index') === false) {
  174. return $this->_scaffoldError();
  175. }
  176. }
  177. /**
  178. * Renders an add or edit action for scaffolded model.
  179. *
  180. * @param string $action Action (add or edit)
  181. * @return mixed A rendered view with a form to edit or add a record in the Models database table
  182. */
  183. protected function _scaffoldForm($action = 'edit') {
  184. $this->controller->viewVars['scaffoldFields'] = array_merge(
  185. $this->controller->viewVars['scaffoldFields'],
  186. array_keys($this->ScaffoldModel->hasAndBelongsToMany)
  187. );
  188. $this->controller->render($action, $this->layout);
  189. }
  190. /**
  191. * Saves or updates the scaffolded model.
  192. *
  193. * @param CakeRequest $request Request Object for scaffolding
  194. * @param string $action add or edit
  195. * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
  196. * @throws NotFoundException
  197. */
  198. protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
  199. $formAction = 'edit';
  200. $success = __d('cake', 'updated');
  201. if ($action === 'add') {
  202. $formAction = 'add';
  203. $success = __d('cake', 'saved');
  204. }
  205. if ($this->controller->beforeScaffold($action)) {
  206. if ($action == 'edit') {
  207. if (isset($request->params['pass'][0])) {
  208. $this->ScaffoldModel->id = $request['pass'][0];
  209. }
  210. if (!$this->ScaffoldModel->exists()) {
  211. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  212. }
  213. }
  214. if (!empty($request->data)) {
  215. if ($action == 'create') {
  216. $this->ScaffoldModel->create();
  217. }
  218. if ($this->ScaffoldModel->save($request->data)) {
  219. if ($this->controller->afterScaffoldSave($action)) {
  220. $message = __d('cake',
  221. 'The %1$s has been %2$s',
  222. Inflector::humanize($this->modelKey),
  223. $success
  224. );
  225. return $this->_sendMessage($message);
  226. } else {
  227. return $this->controller->afterScaffoldSaveError($action);
  228. }
  229. } else {
  230. if ($this->_validSession) {
  231. $this->controller->Session->setFlash(__d('cake', 'Please correct errors below.'));
  232. }
  233. }
  234. }
  235. if (empty($request->data)) {
  236. if ($this->ScaffoldModel->id) {
  237. $this->controller->data = $request->data = $this->ScaffoldModel->read();
  238. } else {
  239. $this->controller->data = $request->data = $this->ScaffoldModel->create();
  240. }
  241. }
  242. foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
  243. $varName = Inflector::variable(Inflector::pluralize(
  244. preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
  245. ));
  246. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  247. }
  248. foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
  249. $varName = Inflector::variable(Inflector::pluralize($assocName));
  250. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  251. }
  252. return $this->_scaffoldForm($formAction);
  253. } elseif ($this->controller->scaffoldError($action) === false) {
  254. return $this->_scaffoldError();
  255. }
  256. }
  257. /**
  258. * Performs a delete on given scaffolded Model.
  259. *
  260. * @param CakeRequest $request Request for scaffolding
  261. * @return mixed Success on delete, error if delete fails
  262. * @throws MethodNotAllowedException When HTTP method is not a DELETE
  263. * @throws NotFoundException When id being deleted does not exist.
  264. */
  265. protected function _scaffoldDelete(CakeRequest $request) {
  266. if ($this->controller->beforeScaffold('delete')) {
  267. if (!$request->is('post')) {
  268. throw new MethodNotAllowedException();
  269. }
  270. $id = false;
  271. if (isset($request->params['pass'][0])) {
  272. $id = $request->params['pass'][0];
  273. }
  274. $this->ScaffoldModel->id = $id;
  275. if (!$this->ScaffoldModel->exists()) {
  276. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
  277. }
  278. if ($this->ScaffoldModel->delete()) {
  279. $message = __d('cake', 'The %1$s with id: %2$s has been deleted.', Inflector::humanize($this->modelClass), $id);
  280. return $this->_sendMessage($message);
  281. } else {
  282. $message = __d('cake',
  283. 'There was an error deleting the %1$s with id: %2$s',
  284. Inflector::humanize($this->modelClass),
  285. $id
  286. );
  287. return $this->_sendMessage($message);
  288. }
  289. } elseif ($this->controller->scaffoldError('delete') === false) {
  290. return $this->_scaffoldError();
  291. }
  292. }
  293. /**
  294. * Sends a message to the user. Either uses Sessions or flash messages depending
  295. * on the availability of a session
  296. *
  297. * @param string $message Message to display
  298. * @return void
  299. */
  300. protected function _sendMessage($message) {
  301. if ($this->_validSession) {
  302. $this->controller->Session->setFlash($message);
  303. $this->controller->redirect($this->redirect);
  304. } else {
  305. $this->controller->flash($message, $this->redirect);
  306. }
  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 CakeRequest $request Request object for scaffolding
  322. * @return mixed A rendered view of scaffold action, or showing the error
  323. * @throws MissingActionException When methods are not scaffolded.
  324. * @throws MissingDatabaseException When the database connection is undefined.
  325. */
  326. protected function _scaffold(CakeRequest $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 MissingActionException(array(
  373. 'controller' => $this->controller->name,
  374. 'action' => $request->action
  375. ));
  376. }
  377. } else {
  378. throw new 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 $key => $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. }