FixtureController.php 8.87 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(), [
Mark committed
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 77
	 * @param array $fixtures
	 * @throws \yii\console\Exception
Mark committed
78
	 */
Mark committed
79
	public function actionLoad(array $fixtures, array $except = [])
Mark committed
80
	{
Mark committed
81 82 83 84 85 86 87 88 89 90 91 92
		$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"
93
				. "Check that files with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"."
Mark committed
94
			);
Mark committed
95 96
		}

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

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

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

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

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

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

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

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

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

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

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

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

154 155 156 157
	/**
	 * Notifies user that fixtures were successfully loaded.
	 * @param array $fixtures
	 */
Mark committed
158 159 160 161 162 163 164 165 166 167 168 169
	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)
170
	{
171
		$this->stdout("Fixtures were successfully unloaded from namespace:\n", Console::FG_YELLOW);
172
		$this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
Mark committed
173 174
		$this->outputList($fixtures);
	}
175

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return $foundFixtures;
	}

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

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

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

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

		return $config;
	}

312 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
}