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

namespace yii\console\controllers;

use Yii;
use yii\console\Controller;
12
use yii\console\Exception;
Mark committed
13
use yii\helpers\FileHelper;
Mark committed
14
use yii\helpers\Console;
Mark committed
15 16
use yii\test\FixtureTrait;
use yii\helpers\Inflector;
Mark committed
17 18

/**
Mark committed
19
 * This command manages loading and unloading fixtures.
Mark committed
20 21
 * You can specify different options of this command to point fixture manager
 * to the specific tables of the different database connections.
Qiang Xue committed
22
 *
Mark committed
23
 * To use this command simply configure your console.php config like this:
Qiang Xue committed
24
 *
Mark committed
25
 * ~~~
Qiang Xue committed
26 27 28 29 30 31 32
 * 'db' => [
 *     'class' => 'yii\db\Connection',
 *     'dsn' => 'mysql:host=localhost;dbname={your_database}',
 *     'username' => '{your_db_user}',
 *     'password' => '',
 *     'charset' => 'utf8',
 * ],
Mark committed
33
 * ~~~
Qiang Xue committed
34
 *
Mark committed
35
 * ~~~
Mark committed
36
 * #load fixtures under $fixturePath from UsersFixture class with default namespace "tests\unit\fixtures"
Mark committed
37
 * yii fixture/apply User
Qiang Xue committed
38
 *
Mark committed
39
 * #also a short version of this command (generate action is default)
Mark committed
40
 * yii fixture User
Qiang Xue committed
41
 *
Mark committed
42
 * #load fixtures under $fixturePath with the different database connection
Mark committed
43
 * yii fixture/apply User --db=someOtherDbConneciton
Qiang Xue committed
44
 *
Mark committed
45
 * #load fixtures under different $fixturePath.
Mark committed
46
 * yii fixture/apply User --namespace=alias\my\custom\namespace\goes\here
Mark committed
47
 * ~~~
Qiang Xue committed
48
 *
Mark committed
49 50 51 52 53
 * @author Mark Jebri <mark.github@yandex.ru>
 * @since 2.0
 */
class FixtureController extends Controller
{
Mark committed
54
	
Mark committed
55 56
	use FixtureTrait;

Mark committed
57 58 59 60
	/**
	 * type of fixture apply to database
	 */
	const APPLY_ALL = 'all';
Mark committed
61 62 63 64 65 66

	/**
	 * @var string controller default action ID.
	 */
	public $defaultAction = 'apply';
	/**
Mark committed
67
	 * @var string id of the database connection component of the application.
Mark committed
68 69 70
	 */
	public $db = 'db';

Mark committed
71 72 73 74
	/**
	 * @var string default namespace to search fixtures in
	 */
	public $namespace = 'tests\unit\fixtures';
Carsten Brandt committed
75

Mark committed
76 77 78 79 80 81 82
	/**
	 * Returns the names of the global options for this command.
	 * @return array the names of the global options for this command.
	 */
	public function globalOptions()
	{
		return array_merge(parent::globalOptions(), [
83
			'db','namespace'
Mark committed
84 85 86 87
		]);
	}

	/**
88 89 90
	 * Apply given fixture to the table. You can load several fixtures specifying
	 * their names separated with commas, like: tbl_user,tbl_profile. Be sure there is no
	 * whitespace between tables names.
Carsten Brandt committed
91 92
	 * @param array $fixtures
	 * @throws \yii\console\Exception
Mark committed
93
	 */
Mark committed
94
	public function actionApply(array $fixtures, array $except = [])
Mark committed
95
	{
Mark committed
96 97 98 99 100 101 102 103 104 105 106 107
		$foundFixtures = $this->findFixtures($fixtures);

		if (!$this->needToApplyAll($fixtures[0])) {
			$notFoundFixtures = array_diff($fixtures, $foundFixtures);

			if ($notFoundFixtures) {
				$this->notifyNotFound($notFoundFixtures);
			}
		}

		if (!$foundFixtures) {
			throw new Exception("No files were found by name: \"" . implode(', ', $fixtures) . "\".\n"
108
				. "Check that files with these name exists, under fixtures path: \n\"" . Yii::getAlias($this->getFixturePath()) . "\"."
Mark committed
109
			);
Mark committed
110 111
		}

Mark committed
112
		if (!$this->confirmApply($foundFixtures, $except)) {
Mark committed
113
			return;
Mark committed
114
		}
Mark committed
115

Mark committed
116
		$fixtures = $this->getFixturesConfig(array_diff($foundFixtures, $except));
Mark committed
117

Mark committed
118
		if (!$fixtures) {
Mark committed
119
			throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"'.'');
Mark committed
120
		}
Mark committed
121 122 123

		$transaction = Yii::$app->db->beginTransaction();

Mark committed
124
		try {
Mark committed
125 126 127
			$this->getDbConnection()->createCommand()->checkIntegrity(false)->execute();
			$this->loadFixtures($fixtures);
			$this->getDbConnection()->createCommand()->checkIntegrity(true)->execute();
Mark committed
128
			$transaction->commit();
Mark committed
129
		} catch (\Exception $e) {
Mark committed
130 131 132 133 134
			$transaction->rollback();
			$this->stdout("Exception occured, transaction rollback. Tables will be in same state.\n", Console::BG_RED);
			throw $e;
		}
		$this->notifySuccess($foundFixtures);
Mark committed
135 136 137
	}

	/**
Mark committed
138
	 * Unloads given fixtures. You can clear environment and unload multiple fixtures by specifying
139 140
	 * their names separated with commas, like: tbl_user,tbl_profile. Be sure there is no
	 * whitespace between tables names.
Mark committed
141 142
	 * @param array|string $fixtures
	 * @param array|string $except
Mark committed
143
	 */
Mark committed
144 145 146 147 148 149 150 151 152 153
	public function actionClear(array $fixtures, array $except = [])
	{
		$foundFixtures = $this->findFixtures($fixtures);

		if (!$this->needToApplyAll($fixtures[0])) {
			$notFoundFixtures = array_diff($fixtures, $foundFixtures);

			if ($notFoundFixtures) {
				$this->notifyNotFound($notFoundFixtures);
			}
Mark committed
154 155
		}

Mark committed
156 157
		if (!$foundFixtures) {
			throw new Exception("No files were found by name: \"" . implode(', ', $fixtures) . "\".\n"
158
				. "Check that fixtures with these name exists, under fixtures path: \n\"" . Yii::getAlias($this->getFixturePath()) . "\"."
Mark committed
159 160 161 162
			);
		}

		if (!$this->confirmClear($foundFixtures, $except)) {
Mark committed
163 164 165
			return;
		}

Mark committed
166
		$fixtures = $this->getFixturesConfig(array_diff($foundFixtures, $except));
Mark committed
167 168

		if (!$fixtures) {
Mark committed
169
			throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
Mark committed
170
		}
Mark committed
171

Mark committed
172 173
		$transaction = Yii::$app->db->beginTransaction();

Mark committed
174
		try {
Mark committed
175 176
			$this->getDbConnection()->createCommand()->checkIntegrity(false)->execute();

Mark committed
177 178 179
			foreach($fixtures as $fixtureConfig) {
				$fixture = Yii::createObject($fixtureConfig);
				$fixture->unload();
180
				$this->stdout("\tFixture \"{$fixture::className()}\" was successfully unloaded. \n", Console::FG_GREEN);
Mark committed
181 182 183 184 185
			}

			$this->getDbConnection()->createCommand()->checkIntegrity(true)->execute();
			$transaction->commit();

Mark committed
186
		} catch (\Exception $e) {
Mark committed
187 188 189
			$transaction->rollback();
			$this->stdout("Exception occured, transaction rollback. Tables will be in same state.\n", Console::BG_RED);
			throw $e;
Mark committed
190
		}
Mark committed
191 192 193 194
	}

	/**
	 * Returns database connection component
Qiang Xue committed
195
	 * @return \yii\db\Connection
Mark committed
196
	 * @throws yii\console\Exception if [[db]] is invalid.
Mark committed
197 198 199 200 201
	 */
	public function getDbConnection()
	{
		$db = Yii::$app->getComponent($this->db);

Carsten Brandt committed
202
		if ($db === null) {
203
			throw new Exception("There is no database connection component with id \"{$this->db}\".");
Mark committed
204 205 206 207 208
		}

		return $db;
	}

209 210 211 212 213 214
	/**
	 * Notifies user that fixtures were successfully loaded.
	 * @param array $fixtures
	 */
	private function notifySuccess($fixtures)
	{
215 216
		$this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW);
		$this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
Mark committed
217 218
		$this->outputList($fixtures);
	}
219

Mark committed
220 221 222 223 224 225 226
	/**
	 * Notifies user that fixtures were not found under fixtures path.
	 * @param array $fixtures
	 */
	private function notifyNotFound($fixtures)
	{
		$this->stdout("Some fixtures were not found under path:\n", Console::BG_RED);
227
		$this->stdout("\t" . Yii::getAlias($this->getFixturePath()) . "\n\n", Console::FG_GREEN);
Mark committed
228
		$this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
Mark committed
229 230 231 232
		$this->outputList($fixtures);
		$this->stdout("\n");
	}

Mark committed
233 234 235
	/**
	 * Prompts user with confirmation if fixtures should be loaded.
	 * @param array $fixtures
Mark committed
236
	 * @param array $except
Mark committed
237 238
	 * @return boolean
	 */
Mark committed
239
	private function confirmApply($fixtures, $except)
Mark committed
240
	{
Mark committed
241 242 243 244
		$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
		$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);

		$this->stdout("Fixtures below will be loaded:\n\n", Console::FG_YELLOW);
Mark committed
245
		$this->outputList($fixtures);
Mark committed
246 247 248 249 250 251

		if (count($except)) {
			$this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
			$this->outputList($except);
		}

252
		return $this->confirm("\nLoad above fixtures?");
Mark committed
253 254 255
	}

	/**
Mark committed
256 257
	 * Prompts user with confirmation for fixtures that should be unloaded.
	 * @param array $fixtures
Mark committed
258
	 * @param array $except
Mark committed
259 260
	 * @return boolean
	 */
Mark committed
261
	private function confirmClear($fixtures, $except)
Mark committed
262
	{
Mark committed
263 264 265 266 267
		$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
		$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);

		$this->stdout("Fixtures below will be unloaded:\n\n", Console::FG_YELLOW);
		$this->outputList($fixtures);
Mark committed
268 269

		if (count($except)) {
Mark committed
270
			$this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
Mark committed
271 272 273
			$this->outputList($except);
		}

Mark committed
274
		return $this->confirm("\nUnload fixtures?");
Mark committed
275 276 277 278 279 280 281 282 283
	}

	/**
	 * Outputs data to the console as a list.
	 * @param array $data
	 */
	private function outputList($data)
	{
		foreach($data as $index => $item) {
Mark committed
284
			$this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
285 286
		}
	}
Mark committed
287 288 289 290 291 292 293 294 295 296 297 298 299

	/**
	 * Checks if needed to apply all fixtures.
	 * @param string $fixture
	 * @return bool
	 */
	public function needToApplyAll($fixture)
	{
		return $fixture == self::APPLY_ALL;
	}

	/**
	 * @param array $fixtures
Qiang Xue committed
300
	 * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists.
Mark committed
301 302 303
	 */
	private function findFixtures(array $fixtures)
	{
304
		$fixturesPath = Yii::getAlias($this->getFixturePath());
305

Mark committed
306
		$filesToSearch = ['*Fixture.php'];
307 308
		if (!$this->needToApplyAll($fixtures[0])) {
			$filesToSearch = [];
Mark committed
309
			foreach ($fixtures as $fileName) {
Mark committed
310
				$filesToSearch[] = $fileName . 'Fixture.php';
Mark committed
311 312
			}
		}
Alexander Makarov committed
313 314

		$files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]);
Mark committed
315 316
		$foundFixtures = [];

Alexander Makarov committed
317
		foreach ($files as $fixture) {
Mark committed
318
			$foundFixtures[] = basename($fixture , 'Fixture.php');
Mark committed
319 320 321 322 323
		}

		return $foundFixtures;
	}

Mark committed
324 325 326 327 328
	/**
	 * Returns valid fixtures config that can be used to load them.
	 * @param array $fixtures fixtures to configure
	 * @return array
	 */
Mark committed
329
	private function getFixturesConfig($fixtures)
Mark committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	{
		$config = [];

		foreach($fixtures as $fixture) {

			$fullClassName = $this->namespace . '\\' . $fixture . 'Fixture';

			if (class_exists($fullClassName)) {
				$config[Inflector::camel2id($fixture, '_')] = [
					'class' => $fullClassName,
				];
			}
		}

		return $config;
	}

347 348 349 350 351 352 353 354 355
	/**
	 * Returns fixture path that determined on fixtures namespace.
	 * @return string fixture path
	 */
	private function getFixturePath()
	{
		return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace));
	}

Mark committed
356
}