AppController.php 9.09 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8 9 10
namespace yii\console\controllers;

use yii\console\Controller;
11
use yii\base\Exception;
12

Qiang Xue committed
13
/**
14
 * This command creates an Yii Web application at the specified location.
Qiang Xue committed
15 16
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
17
 * @author Alexander Makarov <sam@rmcreative.ru>
18
 * @since 2.0
Qiang Xue committed
19
 */
20
class AppController extends Controller
Qiang Xue committed
21 22
{
	private $_rootPath;
23 24 25 26
	private $_config;

	/**
	 * @var string custom template path. If specified, templates will be
27
	 * searched there additionally to `framework/console/webapp`.
28 29 30 31 32 33 34 35 36 37 38 39 40
	 */
	public $templatesPath;

	/**
	 * @var string application type. If not specified default application
	 * skeleton will be used.
	 */
	public $type = 'default';

	public function init()
	{
		parent::init();

resurtm committed
41
		if ($this->templatesPath && !is_dir($this->templatesPath)) {
42 43 44
			throw new Exception('--templatesPath "'.$this->templatesPath.'" does not exist or can not be read.');
		}
	}
Qiang Xue committed
45

46 47 48 49 50 51 52
	public function globalOptions()
	{
		return array('templatesPath', 'type');
	}

	public function actionIndex()
	{
53
		$this->forward('help/index', array('-args' => array('app/create')));
54 55
	}

Qiang Xue committed
56
	/**
57 58
	 * Generates Yii application at the path specified via appPath parameter.
	 *
Alexander Makarov committed
59
	 * @param string $path the directory where the new application will be created.
60 61
	 * If the directory does not exist, it will be created. After the application
	 * is created, please make sure the directory has enough permissions.
62 63
	 *
	 * @throws \yii\base\Exception if path specified is not valid
64
	 * @return integer the exit status
Qiang Xue committed
65
	 */
66
	public function actionCreate($path)
Qiang Xue committed
67
	{
68
		$path = strtr($path, '/\\', DIRECTORY_SEPARATOR);
resurtm committed
69
		if (strpos($path, DIRECTORY_SEPARATOR) === false) {
70 71 72
			$path = '.'.DIRECTORY_SEPARATOR.$path;
		}
		$dir = rtrim(realpath(dirname($path)), '\\/');
resurtm committed
73
		if ($dir === false || !is_dir($dir)) {
74
			throw new Exception("The directory '$path' is not valid. Please make sure the parent directory exists.");
75
		}
76

resurtm committed
77
		if (basename($path) === '.') {
78
			$this->_rootPath = $path = $dir;
resurtm committed
79
		} else {
80 81
			$this->_rootPath = $path = $dir.DIRECTORY_SEPARATOR.basename($path);
		}
82

resurtm committed
83
		if ($this->confirm("Create \"$this->type\" application under '$path'?")) {
84 85 86
			$sourceDir = $this->getSourceDir();
			$config = $this->getConfig();

Qiang Xue committed
87
			$list = $this->buildFileList($sourceDir, $path);
88

resurtm committed
89 90 91
			if (is_array($config)) {
				foreach ($config as $file => $settings) {
					if (isset($settings['handler'])) {
92 93 94 95 96
						$list[$file]['callback'] = $settings['handler'];
					}
				}
			}

Qiang Xue committed
97
			$this->copyFiles($list);
98

resurtm committed
99 100 101
			if (is_array($config)) {
				foreach ($config as $file => $settings) {
					if (isset($settings['permissions'])) {
102 103 104 105 106
						@chmod($path.'/'.$file, $settings['permissions']);
					}
				}
			}

Qiang Xue committed
107 108 109 110
			echo "\nYour application has been created successfully under {$path}.\n";
		}
	}

111
	/**
112 113
	 * @throws \yii\base\Exception if source directory wasn't located
	 * @return string
114
	 */
115
	protected function getSourceDir()
Qiang Xue committed
116
	{
117 118 119
		$customSource = realpath($this->templatesPath.'/'.$this->type);
		$defaultSource = realpath($this->getDefaultTemplatesPath().'/'.$this->type);

resurtm committed
120
		if ($customSource) {
121
			return $customSource;
resurtm committed
122
		} elseif ($defaultSource) {
123
			return $defaultSource;
resurtm committed
124
		} else {
125 126
			throw new Exception('Unable to locate the source directory for "'.$this->type.'".');
		}
Qiang Xue committed
127 128
	}

129
	/**
130
	 * @return string default templates path
131
	 */
132
	protected function getDefaultTemplatesPath()
Qiang Xue committed
133
	{
134
		return realpath(__DIR__.'/../webapp');
Qiang Xue committed
135 136
	}

137
	/**
138 139 140 141
	 * @return array|null template configuration
	 */
	protected function getConfig()
	{
resurtm committed
142 143
		if ($this->_config === null) {
			$this->_config = require $this->getDefaultTemplatesPath() . '/config.php';
resurtm committed
144
			if ($this->templatesPath && file_exists($this->templatesPath)) {
resurtm committed
145
				$this->_config = array_merge($this->_config, require $this->templatesPath . '/config.php');
146 147
			}
		}
resurtm committed
148
		if (isset($this->_config[$this->type])) {
149 150 151 152 153 154 155 156
			return $this->_config[$this->type];
		}
	}

	/**
	 * @param string $source path to source file
	 * @param string $pathTo path to file we want to get relative path for
	 * @param string $varName variable name w/o $ to replace value with relative path for
157
	 *
Alexander Makarov committed
158
	 * @return string target file contents
159
	 */
160
	public function replaceRelativePath($source, $pathTo, $varName)
Qiang Xue committed
161
	{
162
		$content = file_get_contents($source);
163 164 165 166 167 168
		$relativeFile = str_replace($this->getSourceDir(), '', $source);

		$relativePath = $this->getRelativePath($pathTo, $this->_rootPath.$relativeFile);
		$relativePath = str_replace('\\', '\\\\', $relativePath);

		return preg_replace('/\$'.$varName.'\s*=(.*?);/', "\$".$varName."=$relativePath;", $content);
Qiang Xue committed
169 170
	}

171
	/**
Qiang Xue committed
172 173
	 * @param string $path1 absolute path
	 * @param string $path2 absolute path
174 175 176 177
	 *
	 * @return string relative path
	 */
	protected function getRelativePath($path1, $path2)
Qiang Xue committed
178
	{
179 180 181 182
		$segs1 = explode(DIRECTORY_SEPARATOR, $path1);
		$segs2 = explode(DIRECTORY_SEPARATOR, $path2);
		$n1 = count($segs1);
		$n2 = count($segs2);
Qiang Xue committed
183

resurtm committed
184 185
		for ($i = 0; $i < $n1 && $i < $n2; ++$i) {
			if ($segs1[$i] !== $segs2[$i]) {
Qiang Xue committed
186
				break;
187
			}
Qiang Xue committed
188 189
		}

resurtm committed
190 191
		if ($i === 0) {
			return "'" . $path1 . "'";
192
		}
resurtm committed
193 194 195
		$up = '';
		for ($j = $i; $j < $n2 - 1; ++$j) {
			$up .= '/..';
196
		}
resurtm committed
197 198
		for(; $i < $n1 - 1; ++$i) {
			$up .= '/' . $segs1[$i];
199
		}
Qiang Xue committed
200

resurtm committed
201
		return '__DIR__.\'' . $up . '/' . basename($path1) . '\'';
Qiang Xue committed
202
	}
Qiang Xue committed
203 204 205 206


	/**
	 * Copies a list of files from one place to another.
resurtm committed
207
	 * @param array $fileList the list of files to be copied (name => spec).
Qiang Xue committed
208 209 210 211 212 213 214 215
	 * The array keys are names displayed during the copy process, and array values are specifications
	 * for files to be copied. Each array value must be an array of the following structure:
	 * <ul>
	 * <li>source: required, the full path of the file/directory to be copied from</li>
	 * <li>target: required, the full path of the file/directory to be copied to</li>
	 * <li>callback: optional, the callback to be invoked when copying a file. The callback function
	 *   should be declared as follows:
	 *   <pre>
resurtm committed
216
	 *   function foo($source, $params)
Qiang Xue committed
217 218 219 220 221 222 223 224 225 226
	 *   </pre>
	 *   where $source parameter is the source file path, and the content returned
	 *   by the function will be saved into the target file.</li>
	 * <li>params: optional, the parameters to be passed to the callback</li>
	 * </ul>
	 * @see buildFileList
	 */
	protected function copyFiles($fileList)
	{
		$overwriteAll = false;
resurtm committed
227
		foreach ($fileList as $name => $file) {
Qiang Xue committed
228 229 230 231 232
			$source = strtr($file['source'], '/\\', DIRECTORY_SEPARATOR);
			$target = strtr($file['target'], '/\\', DIRECTORY_SEPARATOR);
			$callback = isset($file['callback']) ? $file['callback'] : null;
			$params = isset($file['params']) ? $file['params'] : null;

resurtm committed
233
			if (is_dir($source)) {
Qiang Xue committed
234 235 236 237 238 239
				if (!is_dir($target)) {
					mkdir($target, 0777, true);
				}
				continue;
			}

resurtm committed
240
			if ($callback !== null) {
Qiang Xue committed
241
				$content = call_user_func($callback, $source, $params);
resurtm committed
242
			} else {
Qiang Xue committed
243 244
				$content = file_get_contents($source);
			}
resurtm committed
245 246
			if (is_file($target)) {
				if ($content === file_get_contents($target)) {
Qiang Xue committed
247 248 249
					echo "  unchanged $name\n";
					continue;
				}
resurtm committed
250
				if ($overwriteAll) {
Qiang Xue committed
251 252 253 254 255 256
					echo "  overwrite $name\n";
				}
				else {
					echo "      exist $name\n";
					echo "            ...overwrite? [Yes|No|All|Quit] ";
					$answer = trim(fgets(STDIN));
resurtm committed
257
					if (!strncasecmp($answer, 'q', 1)) {
Qiang Xue committed
258
						return;
resurtm committed
259
					} elseif (!strncasecmp($answer, 'y', 1)) {
Qiang Xue committed
260
						echo "  overwrite $name\n";
resurtm committed
261
					} elseif (!strncasecmp($answer, 'a', 1)) {
Qiang Xue committed
262 263
						echo "  overwrite $name\n";
						$overwriteAll = true;
resurtm committed
264
					} else {
Qiang Xue committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
						echo "       skip $name\n";
						continue;
					}
				}
			}
			else {
				if (!is_dir(dirname($target))) {
					mkdir(dirname($target), 0777, true);
				}
				echo "   generate $name\n";
			}
			file_put_contents($target, $content);
		}
	}

	/**
	 * Builds the file list of a directory.
	 * This method traverses through the specified directory and builds
	 * a list of files and subdirectories that the directory contains.
	 * The result of this function can be passed to {@link copyFiles}.
	 * @param string $sourceDir the source directory
	 * @param string $targetDir the target directory
	 * @param string $baseDir base directory
	 * @param array $ignoreFiles list of the names of files that should
289
	 * be ignored in list building process.
Qiang Xue committed
290
	 * @param array $renameMap hash array of file names that should be
resurtm committed
291
	 * renamed. Example value: array('1.old.txt' => '2.new.txt').
Qiang Xue committed
292 293 294 295 296 297
	 * @return array the file list (see {@link copyFiles})
	 */
	protected function buildFileList($sourceDir, $targetDir, $baseDir='', $ignoreFiles=array(), $renameMap=array())
	{
		$list = array();
		$handle = opendir($sourceDir);
resurtm committed
298 299
		while (($file = readdir($handle)) !== false) {
			if (in_array($file, array('.', '..', '.svn', '.gitignore', '.hgignore')) || in_array($file, $ignoreFiles)) {
Qiang Xue committed
300 301 302 303 304 305 306 307 308
				continue;
			}
			$sourcePath = $sourceDir.DIRECTORY_SEPARATOR.$file;
			$targetPath = $targetDir.DIRECTORY_SEPARATOR.strtr($file, $renameMap);
			$name = $baseDir === '' ? $file : $baseDir.'/'.$file;
			$list[$name] = array(
				'source' => $sourcePath,
				'target' => $targetPath,
			);
resurtm committed
309
			if (is_dir($sourcePath)) {
Qiang Xue committed
310 311 312 313 314 315
				$list = array_merge($list, self::buildFileList($sourcePath, $targetPath, $name, $ignoreFiles, $renameMap));
			}
		}
		closedir($handle);
		return $list;
	}
Zander Baldwin committed
316
}