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

namespace yii\build\controllers;

use yii\console\Controller;
11
use yii\console\Exception;
Qiang Xue committed
12 13 14 15 16 17
use yii\helpers\FileHelper;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
18
class ClassmapController extends Controller
Qiang Xue committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
{
	public $defaultAction = 'create';

	/**
	 * Creates a class map for the core Yii classes.
	 * @param string $root the root path of Yii framework. Defaults to YII_PATH.
	 * @param string $mapFile the file to contain the class map. Defaults to YII_PATH . '/classes.php'.
	 */
	public function actionCreate($root = null, $mapFile = null)
	{
		if ($root === null) {
			$root = YII_PATH;
		}
		$root = FileHelper::normalizePath($root);
		if ($mapFile === null) {
			$mapFile = YII_PATH . '/classes.php';
		}
Alexander Makarov committed
36
		$options = [
Alexander Makarov committed
37
			'filter' => function ($path) {
Qiang Xue committed
38 39 40 41 42 43 44 45
				if (is_file($path)) {
					$file = basename($path);
					if ($file[0] < 'A' || $file[0] > 'Z') {
						return false;
					}
				}
				return null;
			},
46
			'only' => ['*.php'],
Alexander Makarov committed
47
			'except' => [
48 49
				'/Yii.php',
				'/BaseYii.php',
Qiang Xue committed
50
				'/console/',
Alexander Makarov committed
51 52
			],
		];
Qiang Xue committed
53
		$files = FileHelper::findFiles($root, $options);
Alexander Makarov committed
54
		$map = [];
Qiang Xue committed
55
		foreach ($files as $file) {
56
			if (strpos($file, $root) !== 0) {
57
				throw new Exception("Something wrong: $file\n");
Qiang Xue committed
58 59
			}
			$path = str_replace('\\', '/', substr($file, strlen($root)));
60
			$map[$path] = "\t'yii" . substr(str_replace('/', '\\', $path), 0, -4) . "' => YII_PATH . '$path',";
Qiang Xue committed
61
		}
62
		ksort($map);
Qiang Xue committed
63 64 65 66 67 68
		$map = implode("\n", $map);
		$output = <<<EOD
<?php
/**
 * Yii core class map.
 *
69
 * This file is automatically generated by the "build classmap" command under the "build" folder.
Qiang Xue committed
70 71 72 73 74 75 76
 * Do not modify it directly.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

Alexander Makarov committed
77
return [
Qiang Xue committed
78
$map
Alexander Makarov committed
79
];
Qiang Xue committed
80 81 82

EOD;
		if (is_file($mapFile) && file_get_contents($mapFile) === $output) {
83
			echo "Nothing changed.\n";
Qiang Xue committed
84 85
		} else {
			file_put_contents($mapFile, $output);
86
			echo "Class map saved in $mapFile\n";
Qiang Xue committed
87 88 89
		}
	}
}