summaryrefslogtreecommitdiff
path: root/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Console/Command/ConsoleShell.php
blob: 222ee333d4375a4a4bda11a43635998b7f277c0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         CakePHP(tm) v 1.2.0.5012
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('AppShell', 'Console/Command');

/**
 * Provides a very basic 'interactive' console for CakePHP apps.
 *
 * @package       Cake.Console.Command
 */
class ConsoleShell extends AppShell {

/**
 * Available binding types
 *
 * @var array
 */
	public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');

/**
 * Chars that describe invalid commands
 *
 * @var array
 */
	public $badCommandChars = array('$', ';');

/**
 * Available models
 *
 * @var array
 */
	public $models = array();

/**
 * Override startup of the Shell
 *
 * @return void
 */
	public function startup() {
		App::uses('Dispatcher', 'Routing');
		$this->Dispatcher = new Dispatcher();
		$this->models = App::objects('Model');

		foreach ($this->models as $model) {
			$class = $model;
			$this->models[$model] = $class;
			App::uses($class, 'Model');
			$this->{$class} = new $class();
		}
		$this->out(__d('cake_console', 'Model classes:'));
		$this->hr();

		foreach ($this->models as $model) {
			$this->out(" - {$model}");
		}
		if (!$this->_loadRoutes()) {
			$this->out(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
		}
	}

/**
 * Prints the help message
 *
 * @return void
 */
	public function help() {
		$out  = 'Console help:';
		$out .= '-------------';
		$out .= 'The interactive console is a tool for testing parts of your app before you';
		$out .= 'write code.';
		$out .= "\n";
		$out .= 'Model testing:';
		$out .= 'To test model results, use the name of your model without a leading $';
		$out .= 'e.g. Foo->find("all")';
		$out .= "\n";
		$out .= 'To dynamically set associations, you can do the following:';
		$out .= "\tModelA bind <association> ModelB";
		$out .= "where the supported associations are hasOne, hasMany, belongsTo, hasAndBelongsToMany";
		$out .= "\n";
		$out .= 'To dynamically remove associations, you can do the following:';
		$out .= "\t ModelA unbind <association> ModelB";
		$out .= "where the supported associations are the same as above";
		$out .= "\n";
		$out .= "To save a new field in a model, you can do the following:";
		$out .= "\tModelA->save(array('foo' => 'bar', 'baz' => 0))";
		$out .= "where you are passing a hash of data to be saved in the format";
		$out .= "of field => value pairs";
		$out .= "\n";
		$out .= "To get column information for a model, use the following:";
		$out .= "\tModelA columns";
		$out .= "which returns a list of columns and their type";
		$out .= "\n";
		$out .= "\n";
		$out .= 'Route testing:';
		$out .= "\n";
		$out .= 'To test URLs against your app\'s route configuration, type:';
		$out .= "\n";
		$out .= "\tRoute <url>";
		$out .= "\n";
		$out .= "where url is the path to your your action plus any query parameters,";
		$out .= "minus the application's base path.  For example:";
		$out .= "\n";
		$out .= "\tRoute /posts/view/1";
		$out .= "\n";
		$out .= "will return something like the following:";
		$out .= "\n";
		$out .= "\tarray(";
		$out .= "\t  [...]";
		$out .= "\t  'controller' => 'posts',";
		$out .= "\t  'action' => 'view',";
		$out .= "\t  [...]";
		$out .= "\t)";
		$out .= "\n";
		$out .= 'Alternatively, you can use simple array syntax to test reverse';
		$out .= 'To reload your routes config (Config/routes.php), do the following:';
		$out .= "\n";
		$out .= "\tRoutes reload";
		$out .= "\n";
		$out .= 'To show all connected routes, do the following:';
		$out .= "\tRoutes show";
		$this->out($out);
	}

/**
 * Override main() to handle action
 *
 * @param string $command
 * @return void
 */
	public function main($command = null) {
		while (true) {
			if (empty($command)) {
				$command = trim($this->in(''));
			}

			switch ($command) {
				case 'help':
					$this->help();
				break;
				case 'quit':
				case 'exit':
					return true;
				break;
				case 'models':
					$this->out(__d('cake_console', 'Model classes:'));
					$this->hr();
					foreach ($this->models as $model) {
						$this->out(" - {$model}");
					}
				break;
				case (preg_match("/^(\w+) bind (\w+) (\w+)/", $command, $tmp) == true):
					foreach ($tmp as $data) {
						$data = strip_tags($data);
						$data = str_replace($this->badCommandChars, "", $data);
					}

					$modelA = $tmp[1];
					$association = $tmp[2];
					$modelB = $tmp[3];

					if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
						$this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
						$this->out(__d('cake_console', "Created %s association between %s and %s",
							$association, $modelA, $modelB));
					} else {
						$this->out(__d('cake_console', "Please verify you are using valid models and association types"));
					}
				break;
				case (preg_match("/^(\w+) unbind (\w+) (\w+)/", $command, $tmp) == true):
					foreach ($tmp as $data) {
						$data = strip_tags($data);
						$data = str_replace($this->badCommandChars, "", $data);
					}

					$modelA = $tmp[1];
					$association = $tmp[2];
					$modelB = $tmp[3];

					// Verify that there is actually an association to unbind
					$currentAssociations = $this->{$modelA}->getAssociated();
					$validCurrentAssociation = false;

					foreach ($currentAssociations as $model => $currentAssociation) {
						if ($model == $modelB && $association == $currentAssociation) {
							$validCurrentAssociation = true;
						}
					}

					if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
						$this->{$modelA}->unbindModel(array($association => array($modelB)));
						$this->out(__d('cake_console', "Removed %s association between %s and %s",
							$association, $modelA, $modelB));
					} else {
						$this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
					}
				break;
				case (strpos($command, "->find") > 0):
					// Remove any bad info
					$command = strip_tags($command);
					$command = str_replace($this->badCommandChars, "", $command);

					// Do we have a valid model?
					list($modelToCheck, $tmp) = explode('->', $command);

					if ($this->_isValidModel($modelToCheck)) {
						$findCommand = "\$data = \$this->$command;";
						@eval($findCommand);

						if (is_array($data)) {
							foreach ($data as $idx => $results) {
								if (is_numeric($idx)) { // findAll() output
									foreach ($results as $modelName => $result) {
										$this->out("$modelName");

										foreach ($result as $field => $value) {
											if (is_array($value)) {
												foreach ($value as $field2 => $value2) {
													$this->out("\t$field2: $value2");
												}

												$this->out();
											} else {
												$this->out("\t$field: $value");
											}
										}
									}
								} else { // find() output
									$this->out($idx);

									foreach ($results as $field => $value) {
										if (is_array($value)) {
											foreach ($value as $field2 => $value2) {
												$this->out("\t$field2: $value2");
											}

											$this->out();
										} else {
											$this->out("\t$field: $value");
										}
									}
								}
							}
						} else {
							$this->out();
							$this->out(__d('cake_console', "No result set found"));
						}
					} else {
						$this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
					}

				break;
				case (strpos($command, '->save') > 0):
					// Validate the model we're trying to save here
					$command = strip_tags($command);
					$command = str_replace($this->badCommandChars, "", $command);
					list($modelToSave, $tmp) = explode("->", $command);

					if ($this->_isValidModel($modelToSave)) {
						// Extract the array of data we are trying to build
						list($foo, $data) = explode("->save", $command);
						$data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
						$saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
						@eval($saveCommand);
						$this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
					}
				break;
				case (preg_match("/^(\w+) columns/", $command, $tmp) == true):
					$modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));

					if ($this->_isValidModel($modelToCheck)) {
						// Get the column info for this model
						$fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
						@eval($fieldsCommand);

						if (is_array($data)) {
							foreach ($data as $field => $type) {
								$this->out("\t{$field}: {$type}");
							}
						}
					} else {
						$this->out(__d('cake_console', "Please verify that you selected a valid model"));
					}
				break;
				case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
					$router = Router::getInstance();
					if (!$this->_loadRoutes()) {
						$this->out(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
						break;
					}
					$this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count($router->routes)));
				break;
				case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
					//$router = Router::getInstance();
					$this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults')));
				break;
				case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
					if ($url = eval('return array' . $tmp[1] . ';')) {
						$this->out(Router::url($url));
					}
				break;
				case (preg_match("/^route\s+(.*)/i", $command, $tmp) == true):
					$this->out(var_export(Router::parse($tmp[1]), true));
				break;
				default:
					$this->out(__d('cake_console', "Invalid command"));
					$this->out();
				break;
			}
			$command = '';
		}
	}

/**
 * Tells if the specified model is included in the list of available models
 *
 * @param string $modelToCheck
 * @return boolean true if is an available model, false otherwise
 */
	protected function _isValidModel($modelToCheck) {
		return in_array($modelToCheck, $this->models);
	}

/**
 * Reloads the routes configuration from app/Config/routes.php, and compiles
 * all routes found
 *
 * @return boolean True if config reload was a success, otherwise false
 */
	protected function _loadRoutes() {
		Router::reload();
		extract(Router::getNamedExpressions());

		if (!@include APP . 'Config' . DS . 'routes.php') {
			return false;
		}
		CakePlugin::routes();

		Router::parse('/');

		foreach (array_keys(Router::getNamedExpressions()) as $var) {
			unset(${$var});
		}

		foreach (Router::$routes as $route) {
			$route->compile();
		}
		return true;
	}

}