FixtureController.php 8.89 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\Console;
Qiang Xue committed
14 15
use yii\helpers\FileHelper;
use yii\test\FixtureTrait;
Mark committed
16 17

/**
Mark committed
18
 * This command manages loading and unloading fixtures.
Qiang Xue committed
19
 *
Mark committed
20
 * ~~~
Mark committed
21
 * #load fixtures from UsersFixture class with default namespace "tests\unit\fixtures"
Mark committed
22
 * yii fixture/load User
Qiang Xue committed
23
 *
Mark committed
24
 * #also a short version of this command (generate action is default)
Mark committed
25
 * yii fixture User
Qiang Xue committed
26
 *
Mark committed
27
 * #load fixtures with different namespace.
Mark committed
28
 * yii fixture/load User --namespace=alias\my\custom\namespace\goes\here
Mark committed
29
 * ~~~
Qiang Xue committed
30
 *
Mark committed
31 32 33 34 35
 * @author Mark Jebri <mark.github@yandex.ru>
 * @since 2.0
 */
class FixtureController extends Controller
{
Qiang Xue committed
36

Mark committed
37 38
	use FixtureTrait;

Mark committed
39 40 41 42
	/**
	 * type of fixture apply to database
	 */
	const APPLY_ALL = 'all';
Mark committed
43 44 45 46

	/**
	 * @var string controller default action ID.
	 */
Mark committed
47
	public $defaultAction = 'load';
Mark committed
48 49 50 51
	/**
	 * @var string default namespace to search fixtures in
	 */
	public $namespace = 'tests\unit\fixtures';
Mark committed
52 53 54 55 56
	/**
	 * @var array global fixtures that should be applied when loading and unloading. By default it is set to `InitDbFixture`
	 * that disables and enables integrity check, so your data can be safely loaded.
	 */
	public $globalFixtures = [
57
		'yii\test\InitDb',
Mark committed
58
	];
Carsten Brandt committed
59

Mark committed
60 61 62 63 64 65 66
	/**
	 * 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(), [
67
			'namespace', 'globalFixtures'
Mark committed
68 69 70 71
		]);
	}

	/**
Mark committed
72 73 74 75
	 * Loads given fixture. You can load several fixtures specifying
	 * their names separated with commas, like: User,UserProfile,MyCustom. Be sure there is no
	 * whitespace between names. Note that if you are loading fixtures to storage, for example: database or nosql,
	 * storage will not be cleared, data will be appended to already existed.
Carsten Brandt committed
76
	 * @param array $fixtures
AlexGx committed
77
	 * @param array $except
Carsten Brandt committed
78
	 * @throws \yii\console\Exception
Mark committed
79
	 */
Mark committed
80
	public function actionLoad(array $fixtures, array $except = [])
Mark committed
81
	{
Mark committed
82 83 84 85 86 87 88 89 90 91 92 93
		$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"
94
				. "Check that files with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"."
Mark committed
95
			);
Mark committed
96 97
		}

Mark committed
98
		if (!$this->confirmLoad($foundFixtures, $except)) {
Mark committed
99
			return;
Mark committed
100
		}
Mark committed
101

Mark committed
102
		$filtered = array_diff($foundFixtures, $except);
103
		$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $filtered));
Mark committed
104

Mark committed
105
		if (!$fixtures) {
Qiang Xue committed
106
			throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
Mark committed
107
		}
Mark committed
108

Mark committed
109 110 111
		$fixturesObjects = $this->createFixtures($fixtures);
		$this->unloadFixtures($fixturesObjects);
		$this->loadFixtures($fixturesObjects);
Mark committed
112
		$this->notifyLoaded($fixtures);
Mark committed
113 114 115
	}

	/**
Mark committed
116
	 * Unloads given fixtures. You can clear environment and unload multiple fixtures by specifying
Mark committed
117
	 * their names separated with commas, like: User,UserProfile,MyCustom. Be sure there is no
Mark committed
118
	 * whitespace between names.
Mark committed
119 120
	 * @param array|string $fixtures
	 * @param array|string $except
Mark committed
121
	 */
Mark committed
122
	public function actionUnload(array $fixtures, array $except = [])
Mark committed
123 124 125 126 127 128 129 130 131
	{
		$foundFixtures = $this->findFixtures($fixtures);

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

			if ($notFoundFixtures) {
				$this->notifyNotFound($notFoundFixtures);
			}
Mark committed
132 133
		}

Mark committed
134 135
		if (!$foundFixtures) {
			throw new Exception("No files were found by name: \"" . implode(', ', $fixtures) . "\".\n"
136
				. "Check that fixtures with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"."
Mark committed
137 138 139
			);
		}

Mark committed
140
		if (!$this->confirmUnload($foundFixtures, $except)) {
Mark committed
141 142 143
			return;
		}

Mark committed
144
		$filtered = array_diff($foundFixtures, $except);
Mark committed
145
		$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $filtered));
Mark committed
146 147

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

Mark committed
151
		$this->unloadFixtures($this->createFixtures($fixtures));
Mark committed
152
		$this->notifyUnloaded($fixtures);
Mark committed
153 154
	}

155 156 157 158
	/**
	 * Notifies user that fixtures were successfully loaded.
	 * @param array $fixtures
	 */
Mark committed
159 160 161 162 163 164 165 166 167 168 169 170
	private function notifyLoaded($fixtures)
	{
		$this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW);
		$this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
		$this->outputList($fixtures);
	}

	/**
	 * Notifies user that fixtures were successfully unloaded.
	 * @param array $fixtures
	 */
	private function notifyUnloaded($fixtures)
171
	{
172
		$this->stdout("Fixtures were successfully unloaded from namespace:\n", Console::FG_YELLOW);
173
		$this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
Mark committed
174 175
		$this->outputList($fixtures);
	}
176

Mark committed
177 178 179 180 181 182 183
	/**
	 * 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);
184
		$this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN);
Mark committed
185
		$this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
Mark committed
186 187 188 189
		$this->outputList($fixtures);
		$this->stdout("\n");
	}

Mark committed
190 191 192
	/**
	 * Prompts user with confirmation if fixtures should be loaded.
	 * @param array $fixtures
Mark committed
193
	 * @param array $except
Mark committed
194 195
	 * @return boolean
	 */
Mark committed
196
	private function confirmLoad($fixtures, $except)
Mark committed
197
	{
Mark committed
198 199 200
		$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
		$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);

Mark committed
201 202 203 204
		if (count($this->globalFixtures)) {
			$this->stdout("Global fixtures will be loaded:\n\n", Console::FG_YELLOW);
			$this->outputList($this->globalFixtures);
		}
Mark committed
205 206

		$this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW);
Mark committed
207
		$this->outputList($fixtures);
Mark committed
208 209 210 211 212 213

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

214
		return $this->confirm("\nLoad above fixtures?");
Mark committed
215 216 217
	}

	/**
Mark committed
218 219
	 * Prompts user with confirmation for fixtures that should be unloaded.
	 * @param array $fixtures
Mark committed
220
	 * @param array $except
Mark committed
221 222
	 * @return boolean
	 */
Mark committed
223
	private function confirmUnload($fixtures, $except)
Mark committed
224
	{
Mark committed
225 226 227
		$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
		$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);

Mark committed
228 229 230 231
		if (count($this->globalFixtures)) {
			$this->stdout("Global fixtures will be unloaded:\n\n", Console::FG_YELLOW);
			$this->outputList($this->globalFixtures);
		}
Mark committed
232 233

		$this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW);
Mark committed
234
		$this->outputList($fixtures);
Mark committed
235 236

		if (count($except)) {
Mark committed
237
			$this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
Mark committed
238 239 240
			$this->outputList($except);
		}

Mark committed
241
		return $this->confirm("\nUnload fixtures?");
Mark committed
242 243 244 245 246 247 248 249
	}

	/**
	 * Outputs data to the console as a list.
	 * @param array $data
	 */
	private function outputList($data)
	{
Qiang Xue committed
250
		foreach ($data as $index => $item) {
Mark committed
251
			$this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
252 253
		}
	}
Mark committed
254 255 256 257 258 259 260 261 262 263 264 265 266

	/**
	 * 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
267
	 * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists.
Mark committed
268 269 270
	 */
	private function findFixtures(array $fixtures)
	{
271
		$fixturesPath = $this->getFixturePath();
272

Mark committed
273
		$filesToSearch = ['*Fixture.php'];
274 275
		if (!$this->needToApplyAll($fixtures[0])) {
			$filesToSearch = [];
Mark committed
276
			foreach ($fixtures as $fileName) {
Mark committed
277
				$filesToSearch[] = $fileName . 'Fixture.php';
Mark committed
278 279
			}
		}
Alexander Makarov committed
280 281

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

Alexander Makarov committed
284
		foreach ($files as $fixture) {
Qiang Xue committed
285
			$foundFixtures[] = basename($fixture, 'Fixture.php');
Mark committed
286 287 288 289 290
		}

		return $foundFixtures;
	}

Mark committed
291 292 293 294 295
	/**
	 * Returns valid fixtures config that can be used to load them.
	 * @param array $fixtures fixtures to configure
	 * @return array
	 */
Mark committed
296
	private function getFixturesConfig($fixtures)
Mark committed
297 298 299
	{
		$config = [];

Qiang Xue committed
300
		foreach ($fixtures as $fixture) {
Mark committed
301

Mark committed
302
			$isNamespaced = (strpos($fixture, '\\') !== false);
Mark committed
303
			$fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
Mark committed
304 305

			if (class_exists($fullClassName)) {
Mark committed
306
				$config[] = $fullClassName;
Mark committed
307 308 309 310 311 312
			}
		}

		return $config;
	}

313 314 315 316 317 318 319 320
	/**
	 * Returns fixture path that determined on fixtures namespace.
	 * @return string fixture path
	 */
	private function getFixturePath()
	{
		return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace));
	}
Mark committed
321
}