You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

490 lines
15KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console\controllers;
  8. use Yii;
  9. use yii\console\Controller;
  10. use yii\console\Exception;
  11. use yii\helpers\Console;
  12. use yii\helpers\FileHelper;
  13. use yii\test\FixtureTrait;
  14. /**
  15. * Manages fixture data loading and unloading.
  16. *
  17. * ```
  18. * #load fixtures from UsersFixture class with default namespace "tests\unit\fixtures"
  19. * yii fixture/load User
  20. *
  21. * #also a short version of this command (generate action is default)
  22. * yii fixture User
  23. *
  24. * #load all fixtures
  25. * yii fixture "*"
  26. *
  27. * #load all fixtures except User
  28. * yii fixture "*, -User"
  29. *
  30. * #load fixtures with different namespace.
  31. * yii fixture/load User --namespace=alias\my\custom\namespace\goes\here
  32. * ```
  33. *
  34. * The `unload` sub-command can be used similarly to unload fixtures.
  35. *
  36. * @author Mark Jebri <mark.github@yandex.ru>
  37. * @since 2.0
  38. */
  39. class FixtureController extends Controller
  40. {
  41. use FixtureTrait;
  42. /**
  43. * @var string controller default action ID.
  44. */
  45. public $defaultAction = 'load';
  46. /**
  47. * @var string default namespace to search fixtures in
  48. */
  49. public $namespace = 'tests\unit\fixtures';
  50. /**
  51. * @var array global fixtures that should be applied when loading and unloading. By default it is set to `InitDbFixture`
  52. * that disables and enables integrity check, so your data can be safely loaded.
  53. */
  54. public $globalFixtures = [
  55. 'yii\test\InitDb',
  56. ];
  57. /**
  58. * @inheritdoc
  59. */
  60. public function options($actionID)
  61. {
  62. return array_merge(parent::options($actionID), [
  63. 'namespace', 'globalFixtures'
  64. ]);
  65. }
  66. /**
  67. * @inheritdoc
  68. * @since 2.0.8
  69. */
  70. public function optionAliases()
  71. {
  72. return array_merge(parent::optionAliases(), [
  73. 'g' => 'globalFixtures',
  74. 'n' => 'namespace',
  75. ]);
  76. }
  77. /**
  78. * Loads the specified fixture data.
  79. * For example,
  80. *
  81. * ```
  82. * # load the fixture data specified by User and UserProfile.
  83. * # any existing fixture data will be removed first
  84. * yii fixture/load "User, UserProfile"
  85. *
  86. * # load all available fixtures found under 'tests\unit\fixtures'
  87. * yii fixture/load "*"
  88. *
  89. * # load all fixtures except User and UserProfile
  90. * yii fixture/load "*, -User, -UserProfile"
  91. * ```
  92. *
  93. * @param array $fixturesInput
  94. * @return int return code
  95. * @throws Exception if the specified fixture does not exist.
  96. */
  97. public function actionLoad(array $fixturesInput = [])
  98. {
  99. if ($fixturesInput === []) {
  100. $this->stdout($this->getHelpSummary() . "\n");
  101. $helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
  102. $this->stdout("Use $helpCommand to get usage info.\n");
  103. return self::EXIT_CODE_NORMAL;
  104. }
  105. $filtered = $this->filterFixtures($fixturesInput);
  106. $except = $filtered['except'];
  107. if (!$this->needToApplyAll($fixturesInput[0])) {
  108. $fixtures = $filtered['apply'];
  109. $foundFixtures = $this->findFixtures($fixtures);
  110. $notFoundFixtures = array_diff($fixtures, $foundFixtures);
  111. if ($notFoundFixtures) {
  112. $this->notifyNotFound($notFoundFixtures);
  113. }
  114. } else {
  115. $foundFixtures = $this->findFixtures();
  116. }
  117. $fixturesToLoad = array_diff($foundFixtures, $except);
  118. if (!$foundFixtures) {
  119. throw new Exception(
  120. "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" .
  121. "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"."
  122. );
  123. }
  124. if (!$fixturesToLoad) {
  125. $this->notifyNothingToLoad($foundFixtures, $except);
  126. return static::EXIT_CODE_NORMAL;
  127. }
  128. if (!$this->confirmLoad($fixturesToLoad, $except)) {
  129. return static::EXIT_CODE_NORMAL;
  130. }
  131. $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad));
  132. if (!$fixtures) {
  133. throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
  134. }
  135. $fixturesObjects = $this->createFixtures($fixtures);
  136. $this->unloadFixtures($fixturesObjects);
  137. $this->loadFixtures($fixturesObjects);
  138. $this->notifyLoaded($fixtures);
  139. return static::EXIT_CODE_NORMAL;
  140. }
  141. /**
  142. * Unloads the specified fixtures.
  143. * For example,
  144. *
  145. * ```
  146. * # unload the fixture data specified by User and UserProfile.
  147. * yii fixture/unload "User, UserProfile"
  148. *
  149. * # unload all fixtures found under 'tests\unit\fixtures'
  150. * yii fixture/unload "*"
  151. *
  152. * # unload all fixtures except User and UserProfile
  153. * yii fixture/unload "*, -User, -UserProfile"
  154. * ```
  155. *
  156. * @param array $fixturesInput
  157. * @return int return code
  158. * @throws Exception if the specified fixture does not exist.
  159. */
  160. public function actionUnload(array $fixturesInput = [])
  161. {
  162. $filtered = $this->filterFixtures($fixturesInput);
  163. $except = $filtered['except'];
  164. if (!$this->needToApplyAll($fixturesInput[0])) {
  165. $fixtures = $filtered['apply'];
  166. $foundFixtures = $this->findFixtures($fixtures);
  167. $notFoundFixtures = array_diff($fixtures, $foundFixtures);
  168. if ($notFoundFixtures) {
  169. $this->notifyNotFound($notFoundFixtures);
  170. }
  171. } else {
  172. $foundFixtures = $this->findFixtures();
  173. }
  174. $fixturesToUnload = array_diff($foundFixtures, $except);
  175. if (!$foundFixtures) {
  176. throw new Exception(
  177. "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" .
  178. "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"."
  179. );
  180. }
  181. if (!$fixturesToUnload) {
  182. $this->notifyNothingToUnload($foundFixtures, $except);
  183. return static::EXIT_CODE_NORMAL;
  184. }
  185. if (!$this->confirmUnload($fixturesToUnload, $except)) {
  186. return static::EXIT_CODE_NORMAL;
  187. }
  188. $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
  189. if (!$fixtures) {
  190. throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
  191. }
  192. $this->unloadFixtures($this->createFixtures($fixtures));
  193. $this->notifyUnloaded($fixtures);
  194. }
  195. /**
  196. * Notifies user that fixtures were successfully loaded.
  197. * @param array $fixtures
  198. */
  199. private function notifyLoaded($fixtures)
  200. {
  201. $this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW);
  202. $this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  203. $this->outputList($fixtures);
  204. }
  205. /**
  206. * Notifies user that there are no fixtures to load according input conditions
  207. * @param array $foundFixtures array of found fixtures
  208. * @param array $except array of names of fixtures that should not be loaded
  209. */
  210. public function notifyNothingToLoad($foundFixtures, $except)
  211. {
  212. $this->stdout("Fixtures to load could not be found according given conditions:\n\n", Console::FG_RED);
  213. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  214. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  215. if (count($foundFixtures)) {
  216. $this->stdout("\nFixtures founded under the namespace:\n\n", Console::FG_YELLOW);
  217. $this->outputList($foundFixtures);
  218. }
  219. if (count($except)) {
  220. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  221. $this->outputList($except);
  222. }
  223. }
  224. /**
  225. * Notifies user that there are no fixtures to unload according input conditions
  226. * @param array $foundFixtures array of found fixtures
  227. * @param array $except array of names of fixtures that should not be loaded
  228. */
  229. public function notifyNothingToUnload($foundFixtures, $except)
  230. {
  231. $this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED);
  232. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  233. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  234. if (count($foundFixtures)) {
  235. $this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW);
  236. $this->outputList($foundFixtures);
  237. }
  238. if (count($except)) {
  239. $this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW);
  240. $this->outputList($except);
  241. }
  242. }
  243. /**
  244. * Notifies user that fixtures were successfully unloaded.
  245. * @param array $fixtures
  246. */
  247. private function notifyUnloaded($fixtures)
  248. {
  249. $this->stdout("\nFixtures were successfully unloaded from namespace: ", Console::FG_YELLOW);
  250. $this->stdout(Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  251. $this->outputList($fixtures);
  252. }
  253. /**
  254. * Notifies user that fixtures were not found under fixtures path.
  255. * @param array $fixtures
  256. */
  257. private function notifyNotFound($fixtures)
  258. {
  259. $this->stdout("Some fixtures were not found under path:\n", Console::BG_RED);
  260. $this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN);
  261. $this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
  262. $this->outputList($fixtures);
  263. $this->stdout("\n");
  264. }
  265. /**
  266. * Prompts user with confirmation if fixtures should be loaded.
  267. * @param array $fixtures
  268. * @param array $except
  269. * @return boolean
  270. */
  271. private function confirmLoad($fixtures, $except)
  272. {
  273. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  274. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  275. if (count($this->globalFixtures)) {
  276. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  277. $this->outputList($this->globalFixtures);
  278. }
  279. if (count($fixtures)) {
  280. $this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW);
  281. $this->outputList($fixtures);
  282. }
  283. if (count($except)) {
  284. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  285. $this->outputList($except);
  286. }
  287. $this->stdout("\nBe aware that:\n", Console::BOLD);
  288. $this->stdout("Applying leads to purging of certain data in the database!\n", Console::FG_RED);
  289. return $this->confirm("\nLoad above fixtures?");
  290. }
  291. /**
  292. * Prompts user with confirmation for fixtures that should be unloaded.
  293. * @param array $fixtures
  294. * @param array $except
  295. * @return boolean
  296. */
  297. private function confirmUnload($fixtures, $except)
  298. {
  299. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  300. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  301. if (count($this->globalFixtures)) {
  302. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  303. $this->outputList($this->globalFixtures);
  304. }
  305. if (count($fixtures)) {
  306. $this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW);
  307. $this->outputList($fixtures);
  308. }
  309. if (count($except)) {
  310. $this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
  311. $this->outputList($except);
  312. }
  313. return $this->confirm("\nUnload fixtures?");
  314. }
  315. /**
  316. * Outputs data to the console as a list.
  317. * @param array $data
  318. */
  319. private function outputList($data)
  320. {
  321. foreach ($data as $index => $item) {
  322. $this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
  323. }
  324. }
  325. /**
  326. * Checks if needed to apply all fixtures.
  327. * @param string $fixture
  328. * @return boolean
  329. */
  330. public function needToApplyAll($fixture)
  331. {
  332. return $fixture === '*';
  333. }
  334. /**
  335. * Finds fixtures to be loaded, for example "User", if no fixtures were specified then all of them
  336. * will be searching by suffix "Fixture.php".
  337. * @param array $fixtures fixtures to be loaded
  338. * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists.
  339. */
  340. private function findFixtures(array $fixtures = [])
  341. {
  342. $fixturesPath = $this->getFixturePath();
  343. $filesToSearch = ['*Fixture.php'];
  344. $findAll = ($fixtures === []);
  345. if (!$findAll) {
  346. $filesToSearch = [];
  347. foreach ($fixtures as $fileName) {
  348. $filesToSearch[] = $fileName . 'Fixture.php';
  349. }
  350. }
  351. $files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]);
  352. $foundFixtures = [];
  353. foreach ($files as $fixture) {
  354. $foundFixtures[] = basename($fixture, 'Fixture.php');
  355. }
  356. return $foundFixtures;
  357. }
  358. /**
  359. * Returns valid fixtures config that can be used to load them.
  360. * @param array $fixtures fixtures to configure
  361. * @return array
  362. */
  363. private function getFixturesConfig($fixtures)
  364. {
  365. $config = [];
  366. foreach ($fixtures as $fixture) {
  367. $isNamespaced = (strpos($fixture, '\\') !== false);
  368. $fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
  369. if (class_exists($fullClassName)) {
  370. $config[] = $fullClassName;
  371. }
  372. }
  373. return $config;
  374. }
  375. /**
  376. * Filters fixtures by splitting them in two categories: one that should be applied and not.
  377. * If fixture is prefixed with "-", for example "-User", that means that fixture should not be loaded,
  378. * if it is not prefixed it is considered as one to be loaded. Returns array:
  379. *
  380. * ```php
  381. * [
  382. * 'apply' => [
  383. * 'User',
  384. * ...
  385. * ],
  386. * 'except' => [
  387. * 'Custom',
  388. * ...
  389. * ],
  390. * ]
  391. * ```
  392. * @param array $fixtures
  393. * @return array fixtures array with 'apply' and 'except' elements.
  394. */
  395. private function filterFixtures($fixtures)
  396. {
  397. $filtered = [
  398. 'apply' => [],
  399. 'except' => [],
  400. ];
  401. foreach ($fixtures as $fixture) {
  402. if (mb_strpos($fixture, '-') !== false) {
  403. $filtered['except'][] = str_replace('-', '', $fixture);
  404. } else {
  405. $filtered['apply'][] = $fixture;
  406. }
  407. }
  408. return $filtered;
  409. }
  410. /**
  411. * Returns fixture path that determined on fixtures namespace.
  412. * @return string fixture path
  413. */
  414. private function getFixturePath()
  415. {
  416. return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace));
  417. }
  418. }