PageRenderTime 40ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Scaffold.php

https://gitlab.com/captain4ever/ufriend_php
PHP | 448 lines | 263 code | 42 blank | 143 comment | 37 complexity | ba2a4b6a04057dc9ff078ccd6b86f1ea MD5 | raw file
  1. <?php
  2. /**
  3. * Scaffold.
  4. *
  5. * Automatic forms and actions generation for rapid web application development.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Controller
  17. * @since Cake v 0.10.0.1076
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. /**
  21. * Scaffolding is a set of automatic actions for starting web development work faster.
  22. *
  23. * Scaffold inspects your database tables, and making educated guesses, sets up a
  24. * number of pages for each of your Models. These pages have data forms that work,
  25. * and afford the web developer an early look at the data, and the possibility to over-ride
  26. * scaffolded actions with custom-made ones.
  27. *
  28. * @package Cake.Controller
  29. * @deprecated 3.0.0 Dynamic scaffolding will be removed and replaced in 3.0
  30. */
  31. class Scaffold {
  32. /**
  33. * Controller object
  34. *
  35. * @var Controller
  36. */
  37. public $controller = null;
  38. /**
  39. * Name of the controller to scaffold
  40. *
  41. * @var string
  42. */
  43. public $name = null;
  44. /**
  45. * Name of current model this view context is attached to
  46. *
  47. * @var string
  48. */
  49. public $model = null;
  50. /**
  51. * Path to View.
  52. *
  53. * @var string
  54. */
  55. public $viewPath;
  56. /**
  57. * Name of layout to use with this View.
  58. *
  59. * @var string
  60. */
  61. public $layout = 'default';
  62. /**
  63. * Request object
  64. *
  65. * @var CakeRequest
  66. */
  67. public $request;
  68. /**
  69. * Valid session.
  70. *
  71. * @var bool
  72. */
  73. protected $_validSession = null;
  74. /**
  75. * List of variables to collect from the associated controller
  76. *
  77. * @var array
  78. */
  79. protected $_passedVars = array(
  80. 'layout', 'name', 'viewPath', 'request'
  81. );
  82. /**
  83. * Title HTML element for current scaffolded view
  84. *
  85. * @var string
  86. */
  87. public $scaffoldTitle = null;
  88. /**
  89. * Construct and set up given controller with given parameters.
  90. *
  91. * @param Controller $controller Controller to scaffold
  92. * @param CakeRequest $request Request parameters.
  93. * @throws MissingModelException
  94. */
  95. public function __construct(Controller $controller, CakeRequest $request) {
  96. $this->controller = $controller;
  97. $count = count($this->_passedVars);
  98. for ($j = 0; $j < $count; $j++) {
  99. $var = $this->_passedVars[$j];
  100. $this->{$var} = $controller->{$var};
  101. }
  102. $this->redirect = array('action' => 'index');
  103. $this->modelClass = $controller->modelClass;
  104. $this->modelKey = $controller->modelKey;
  105. if (!is_object($this->controller->{$this->modelClass})) {
  106. throw new MissingModelException($this->modelClass);
  107. }
  108. $this->ScaffoldModel = $this->controller->{$this->modelClass};
  109. $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath));
  110. $this->scaffoldActions = $controller->scaffold;
  111. $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
  112. $modelClass = $this->controller->modelClass;
  113. $primaryKey = $this->ScaffoldModel->primaryKey;
  114. $displayField = $this->ScaffoldModel->displayField;
  115. $singularVar = Inflector::variable($modelClass);
  116. $pluralVar = Inflector::variable($this->controller->name);
  117. $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
  118. $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
  119. $scaffoldFields = array_keys($this->ScaffoldModel->schema());
  120. $associations = $this->_associations();
  121. $this->controller->set(compact(
  122. 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  123. 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'
  124. ));
  125. $this->controller->set('title_for_layout', $title);
  126. if ($this->controller->viewClass) {
  127. $this->controller->viewClass = 'Scaffold';
  128. }
  129. $this->_validSession = (
  130. isset($this->controller->Session) && $this->controller->Session->valid()
  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 void
  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. }
  226. return $this->controller->afterScaffoldSaveError($action);
  227. }
  228. if ($this->_validSession) {
  229. $this->controller->Session->setFlash(__d('cake', 'Please correct errors below.'));
  230. }
  231. }
  232. if (empty($request->data)) {
  233. if ($this->ScaffoldModel->id) {
  234. $this->controller->data = $request->data = $this->ScaffoldModel->read();
  235. } else {
  236. $this->controller->data = $request->data = $this->ScaffoldModel->create();
  237. }
  238. }
  239. foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
  240. $varName = Inflector::variable(Inflector::pluralize(
  241. preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
  242. ));
  243. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  244. }
  245. foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
  246. $varName = Inflector::variable(Inflector::pluralize($assocName));
  247. $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
  248. }
  249. return $this->_scaffoldForm($formAction);
  250. } elseif ($this->controller->scaffoldError($action) === false) {
  251. return $this->_scaffoldError();
  252. }
  253. }
  254. /**
  255. * Performs a delete on given scaffolded Model.
  256. *
  257. * @param CakeRequest $request Request for scaffolding
  258. * @return mixed Success on delete, error if delete fails
  259. * @throws MethodNotAllowedException When HTTP method is not a DELETE
  260. * @throws NotFoundException When id being deleted does not exist.
  261. */
  262. protected function _scaffoldDelete(CakeRequest $request) {
  263. if ($this->controller->beforeScaffold('delete')) {
  264. if (!$request->is('post')) {
  265. throw new MethodNotAllowedException();
  266. }
  267. $id = false;
  268. if (isset($request->params['pass'][0])) {
  269. $id = $request->params['pass'][0];
  270. }
  271. $this->ScaffoldModel->id = $id;
  272. if (!$this->ScaffoldModel->exists()) {
  273. throw new NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass)));
  274. }
  275. if ($this->ScaffoldModel->delete()) {
  276. $message = __d('cake', 'The %1$s with id: %2$s has been deleted.', Inflector::humanize($this->modelClass), $id);
  277. return $this->_sendMessage($message);
  278. }
  279. $message = __d('cake',
  280. 'There was an error deleting the %1$s with id: %2$s',
  281. Inflector::humanize($this->modelClass),
  282. $id
  283. );
  284. return $this->_sendMessage($message);
  285. } elseif ($this->controller->scaffoldError('delete') === false) {
  286. return $this->_scaffoldError();
  287. }
  288. }
  289. /**
  290. * Sends a message to the user. Either uses Sessions or flash messages depending
  291. * on the availability of a session
  292. *
  293. * @param string $message Message to display
  294. * @return void
  295. */
  296. protected function _sendMessage($message) {
  297. if ($this->_validSession) {
  298. $this->controller->Session->setFlash($message);
  299. return $this->controller->redirect($this->redirect);
  300. }
  301. $this->controller->flash($message, $this->redirect);
  302. }
  303. /**
  304. * Show a scaffold error
  305. *
  306. * @return mixed A rendered view showing the error
  307. */
  308. protected function _scaffoldError() {
  309. return $this->controller->render('error', $this->layout);
  310. }
  311. /**
  312. * When methods are now present in a controller
  313. * scaffoldView is used to call default Scaffold methods if:
  314. * `public $scaffold;` is placed in the controller's class definition.
  315. *
  316. * @param CakeRequest $request Request object for scaffolding
  317. * @return void
  318. * @throws MissingActionException When methods are not scaffolded.
  319. * @throws MissingDatabaseException When the database connection is undefined.
  320. */
  321. protected function _scaffold(CakeRequest $request) {
  322. $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
  323. $prefixes = Configure::read('Routing.prefixes');
  324. $scaffoldPrefix = $this->scaffoldActions;
  325. if (isset($db)) {
  326. if (empty($this->scaffoldActions)) {
  327. $this->scaffoldActions = array(
  328. 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete'
  329. );
  330. } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) {
  331. $this->scaffoldActions = array(
  332. $scaffoldPrefix . '_index',
  333. $scaffoldPrefix . '_list',
  334. $scaffoldPrefix . '_view',
  335. $scaffoldPrefix . '_add',
  336. $scaffoldPrefix . '_create',
  337. $scaffoldPrefix . '_edit',
  338. $scaffoldPrefix . '_update',
  339. $scaffoldPrefix . '_delete'
  340. );
  341. }
  342. if (in_array($request->params['action'], $this->scaffoldActions)) {
  343. if (!empty($prefixes)) {
  344. $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']);
  345. }
  346. switch ($request->params['action']) {
  347. case 'index':
  348. case 'list':
  349. $this->_scaffoldIndex($request);
  350. break;
  351. case 'view':
  352. $this->_scaffoldView($request);
  353. break;
  354. case 'add':
  355. case 'create':
  356. $this->_scaffoldSave($request, 'add');
  357. break;
  358. case 'edit':
  359. case 'update':
  360. $this->_scaffoldSave($request, 'edit');
  361. break;
  362. case 'delete':
  363. $this->_scaffoldDelete($request);
  364. break;
  365. }
  366. } else {
  367. throw new MissingActionException(array(
  368. 'controller' => $this->controller->name,
  369. 'action' => $request->action
  370. ));
  371. }
  372. } else {
  373. throw new MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig));
  374. }
  375. }
  376. /**
  377. * Returns associations for controllers models.
  378. *
  379. * @return array Associations for model
  380. */
  381. protected function _associations() {
  382. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  383. $associations = array();
  384. foreach ($keys as $type) {
  385. foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
  386. $associations[$type][$assocKey]['primaryKey'] =
  387. $this->ScaffoldModel->{$assocKey}->primaryKey;
  388. $associations[$type][$assocKey]['displayField'] =
  389. $this->ScaffoldModel->{$assocKey}->displayField;
  390. $associations[$type][$assocKey]['foreignKey'] =
  391. $assocData['foreignKey'];
  392. list($plugin, $model) = pluginSplit($assocData['className']);
  393. if ($plugin) {
  394. $plugin = Inflector::underscore($plugin);
  395. }
  396. $associations[$type][$assocKey]['plugin'] = $plugin;
  397. $associations[$type][$assocKey]['controller'] =
  398. Inflector::pluralize(Inflector::underscore($model));
  399. if ($type === 'hasAndBelongsToMany') {
  400. $associations[$type][$assocKey]['with'] = $assocData['with'];
  401. }
  402. }
  403. }
  404. return $associations;
  405. }
  406. }