PageRenderTime 34ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Scaffold.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 443 lines | 262 code | 40 blank | 141 comment | 44 complexity | 2ecd2feaa79981b3ba4a6f35c28546ab 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-2011, 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-2011, 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_for_layout = __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. if ($this->controller->viewClass) {
  127. $this->controller->viewClass = 'Scaffold';
  128. }
  129. $this->_validSession = (
  130. isset($this->controller->Session) && $this->controller->Session->valid() != false
  131. );
  132. $this->_scaffold($request);
  133. }
  134. /**
  135. * Renders a view action of scaffolded model.
  136. *
  137. * @param CakeRequest $request Request Object for scaffolding
  138. * @return mixed A rendered view of a row from Models database table
  139. * @throws NotFoundException
  140. */
  141. protected function _scaffoldView(CakeRequest $request) {
  142. if ($this->controller->beforeScaffold('view')) {
  143. if (isset($request->params['pass'][0])) {
  144. $this->ScaffoldModel->id = $request->params['pass'][0];
  145. }
  146. if (!$this->ScaffoldModel->exists()) {
  147. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  148. }
  149. $this->ScaffoldModel->recursive = 1;
  150. $this->controller->request->data = $this->ScaffoldModel->read();
  151. $this->controller->set(
  152. Inflector::variable($this->controller->modelClass), $this->request->data
  153. );
  154. $this->controller->render($this->request['action'], $this->layout);
  155. } elseif ($this->controller->scaffoldError('view') === false) {
  156. return $this->_scaffoldError();
  157. }
  158. }
  159. /**
  160. * Renders index action of scaffolded model.
  161. *
  162. * @param array $params Parameters for scaffolding
  163. * @return mixed A rendered view listing rows from Models database table
  164. */
  165. protected function _scaffoldIndex($params) {
  166. if ($this->controller->beforeScaffold('index')) {
  167. $this->ScaffoldModel->recursive = 0;
  168. $this->controller->set(
  169. Inflector::variable($this->controller->name), $this->controller->paginate()
  170. );
  171. $this->controller->render($this->request['action'], $this->layout);
  172. } elseif ($this->controller->scaffoldError('index') === false) {
  173. return $this->_scaffoldError();
  174. }
  175. }
  176. /**
  177. * Renders an add or edit action for scaffolded model.
  178. *
  179. * @param string $action Action (add or edit)
  180. * @return mixed A rendered view with a form to edit or add a record in the Models database table
  181. */
  182. protected function _scaffoldForm($action = 'edit') {
  183. $this->controller->viewVars['scaffoldFields'] = array_merge(
  184. $this->controller->viewVars['scaffoldFields'],
  185. array_keys($this->ScaffoldModel->hasAndBelongsToMany)
  186. );
  187. $this->controller->render($action, $this->layout);
  188. }
  189. /**
  190. * Saves or updates the scaffolded model.
  191. *
  192. * @param CakeRequest $request Request Object for scaffolding
  193. * @param string $action add or edit
  194. * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
  195. * @throws NotFoundException
  196. */
  197. protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
  198. $formAction = 'edit';
  199. $success = __d('cake', 'updated');
  200. if ($action === 'add') {
  201. $formAction = 'add';
  202. $success = __d('cake', 'saved');
  203. }
  204. if ($this->controller->beforeScaffold($action)) {
  205. if ($action == 'edit') {
  206. if (isset($request->params['pass'][0])) {
  207. $this->ScaffoldModel->id = $request['pass'][0];
  208. }
  209. if (!$this->ScaffoldModel->exists()) {
  210. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey)));
  211. }
  212. }
  213. if (!empty($request->data)) {
  214. if ($action == 'create') {
  215. $this->ScaffoldModel->create();
  216. }
  217. if ($this->ScaffoldModel->save($request->data)) {
  218. if ($this->controller->afterScaffoldSave($action)) {
  219. $message = __d('cake',
  220. 'The %1$s has been %2$s',
  221. Inflector::humanize($this->modelKey),
  222. $success
  223. );
  224. return $this->_sendMessage($message);
  225. } else {
  226. return $this->controller->afterScaffoldSaveError($action);
  227. }
  228. } else {
  229. if ($this->_validSession) {
  230. $this->controller->Session->setFlash(__d('cake', 'Please correct errors below.'));
  231. }
  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, NotFoundException
  262. */
  263. protected function _scaffoldDelete(CakeRequest $request) {
  264. if ($this->controller->beforeScaffold('delete')) {
  265. if (!$request->is('post')) {
  266. throw new MethodNotAllowedException();
  267. }
  268. $id = false;
  269. if (isset($request->params['pass'][0])) {
  270. $id = $request->params['pass'][0];
  271. }
  272. $this->ScaffoldModel->id = $id;
  273. if (!$this->ScaffoldModel->exists()) {
  274. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
  275. }
  276. if ($this->ScaffoldModel->delete()) {
  277. $message = __d('cake', 'The %1$s with id: %2$d has been deleted.', Inflector::humanize($this->modelClass), $id);
  278. return $this->_sendMessage($message);
  279. } else {
  280. $message = __d('cake',
  281. 'There was an error deleting the %1$s with id: %2$d',
  282. Inflector::humanize($this->modelClass),
  283. $id
  284. );
  285. return $this->_sendMessage($message);
  286. }
  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 mixed A rendered view of scaffold action, or showing the error
  321. * @throws MissingActionException, MissingDatabaseException
  322. */
  323. protected function _scaffold(CakeRequest $request) {
  324. $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
  325. $prefixes = Configure::read('Routing.prefixes');
  326. $scaffoldPrefix = $this->scaffoldActions;
  327. if (isset($db)) {
  328. if (empty($this->scaffoldActions)) {
  329. $this->scaffoldActions = array(
  330. 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete'
  331. );
  332. } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) {
  333. $this->scaffoldActions = array(
  334. $scaffoldPrefix . '_index',
  335. $scaffoldPrefix . '_list',
  336. $scaffoldPrefix . '_view',
  337. $scaffoldPrefix . '_add',
  338. $scaffoldPrefix . '_create',
  339. $scaffoldPrefix . '_edit',
  340. $scaffoldPrefix . '_update',
  341. $scaffoldPrefix . '_delete'
  342. );
  343. }
  344. if (in_array($request->params['action'], $this->scaffoldActions)) {
  345. if (!empty($prefixes)) {
  346. $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']);
  347. }
  348. switch ($request->params['action']) {
  349. case 'index':
  350. case 'list':
  351. $this->_scaffoldIndex($request);
  352. break;
  353. case 'view':
  354. $this->_scaffoldView($request);
  355. break;
  356. case 'add':
  357. case 'create':
  358. $this->_scaffoldSave($request, 'add');
  359. break;
  360. case 'edit':
  361. case 'update':
  362. $this->_scaffoldSave($request, 'edit');
  363. break;
  364. case 'delete':
  365. $this->_scaffoldDelete($request);
  366. break;
  367. }
  368. } else {
  369. throw new MissingActionException(array(
  370. 'controller' => $this->controller->name,
  371. 'action' => $request->action
  372. ));
  373. }
  374. } else {
  375. throw new MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig));
  376. }
  377. }
  378. /**
  379. * Returns associations for controllers models.
  380. *
  381. * @return array Associations for model
  382. */
  383. protected function _associations() {
  384. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  385. $associations = array();
  386. foreach ($keys as $key => $type) {
  387. foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
  388. $associations[$type][$assocKey]['primaryKey'] =
  389. $this->ScaffoldModel->{$assocKey}->primaryKey;
  390. $associations[$type][$assocKey]['displayField'] =
  391. $this->ScaffoldModel->{$assocKey}->displayField;
  392. $associations[$type][$assocKey]['foreignKey'] =
  393. $assocData['foreignKey'];
  394. $associations[$type][$assocKey]['controller'] =
  395. Inflector::pluralize(Inflector::underscore($assocData['className']));
  396. if ($type == 'hasAndBelongsToMany') {
  397. $associations[$type][$assocKey]['with'] = $assocData['with'];
  398. }
  399. }
  400. }
  401. return $associations;
  402. }
  403. }