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.

486 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. * @throws Exception if the specified fixture does not exist.
  94. */
  95. public function actionLoad(array $fixturesInput = [])
  96. {
  97. if ($fixturesInput === []) {
  98. $this->stdout($this->getHelpSummary() . "\n");
  99. $helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
  100. $this->stdout("Use $helpCommand to get usage info.\n");
  101. return self::EXIT_CODE_NORMAL;
  102. }
  103. $filtered = $this->filterFixtures($fixturesInput);
  104. $except = $filtered['except'];
  105. if (!$this->needToApplyAll($fixturesInput[0])) {
  106. $fixtures = $filtered['apply'];
  107. $foundFixtures = $this->findFixtures($fixtures);
  108. $notFoundFixtures = array_diff($fixtures, $foundFixtures);
  109. if ($notFoundFixtures) {
  110. $this->notifyNotFound($notFoundFixtures);
  111. }
  112. } else {
  113. $foundFixtures = $this->findFixtures();
  114. }
  115. $fixturesToLoad = array_diff($foundFixtures, $except);
  116. if (!$foundFixtures) {
  117. throw new Exception(
  118. "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" .
  119. "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"."
  120. );
  121. }
  122. if (!$fixturesToLoad) {
  123. $this->notifyNothingToLoad($foundFixtures, $except);
  124. return static::EXIT_CODE_NORMAL;
  125. }
  126. if (!$this->confirmLoad($fixturesToLoad, $except)) {
  127. return static::EXIT_CODE_NORMAL;
  128. }
  129. $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad));
  130. if (!$fixtures) {
  131. throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
  132. }
  133. $fixturesObjects = $this->createFixtures($fixtures);
  134. $this->unloadFixtures($fixturesObjects);
  135. $this->loadFixtures($fixturesObjects);
  136. $this->notifyLoaded($fixtures);
  137. return static::EXIT_CODE_NORMAL;
  138. }
  139. /**
  140. * Unloads the specified fixtures.
  141. * For example,
  142. *
  143. * ```
  144. * # unload the fixture data specified by User and UserProfile.
  145. * yii fixture/unload "User, UserProfile"
  146. *
  147. * # unload all fixtures found under 'tests\unit\fixtures'
  148. * yii fixture/unload "*"
  149. *
  150. * # unload all fixtures except User and UserProfile
  151. * yii fixture/unload "*, -User, -UserProfile"
  152. * ```
  153. *
  154. * @throws Exception if the specified fixture does not exist.
  155. */
  156. public function actionUnload(array $fixturesInput = [])
  157. {
  158. $filtered = $this->filterFixtures($fixturesInput);
  159. $except = $filtered['except'];
  160. if (!$this->needToApplyAll($fixturesInput[0])) {
  161. $fixtures = $filtered['apply'];
  162. $foundFixtures = $this->findFixtures($fixtures);
  163. $notFoundFixtures = array_diff($fixtures, $foundFixtures);
  164. if ($notFoundFixtures) {
  165. $this->notifyNotFound($notFoundFixtures);
  166. }
  167. } else {
  168. $foundFixtures = $this->findFixtures();
  169. }
  170. $fixturesToUnload = array_diff($foundFixtures, $except);
  171. if (!$foundFixtures) {
  172. throw new Exception(
  173. "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" .
  174. "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"."
  175. );
  176. }
  177. if (!$fixturesToUnload) {
  178. $this->notifyNothingToUnload($foundFixtures, $except);
  179. return static::EXIT_CODE_NORMAL;
  180. }
  181. if (!$this->confirmUnload($fixturesToUnload, $except)) {
  182. return static::EXIT_CODE_NORMAL;
  183. }
  184. $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
  185. if (!$fixtures) {
  186. throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
  187. }
  188. $this->unloadFixtures($this->createFixtures($fixtures));
  189. $this->notifyUnloaded($fixtures);
  190. }
  191. /**
  192. * Notifies user that fixtures were successfully loaded.
  193. * @param array $fixtures
  194. */
  195. private function notifyLoaded($fixtures)
  196. {
  197. $this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW);
  198. $this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  199. $this->outputList($fixtures);
  200. }
  201. /**
  202. * Notifies user that there are no fixtures to load according input conditions
  203. * @param array $foundFixtures array of found fixtures
  204. * @param array $except array of names of fixtures that should not be loaded
  205. */
  206. public function notifyNothingToLoad($foundFixtures, $except)
  207. {
  208. $this->stdout("Fixtures to load could not be found according given conditions:\n\n", Console::FG_RED);
  209. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  210. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  211. if (count($foundFixtures)) {
  212. $this->stdout("\nFixtures founded under the namespace:\n\n", Console::FG_YELLOW);
  213. $this->outputList($foundFixtures);
  214. }
  215. if (count($except)) {
  216. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  217. $this->outputList($except);
  218. }
  219. }
  220. /**
  221. * Notifies user that there are no fixtures to unload according input conditions
  222. * @param array $foundFixtures array of found fixtures
  223. * @param array $except array of names of fixtures that should not be loaded
  224. */
  225. public function notifyNothingToUnload($foundFixtures, $except)
  226. {
  227. $this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED);
  228. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  229. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  230. if (count($foundFixtures)) {
  231. $this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW);
  232. $this->outputList($foundFixtures);
  233. }
  234. if (count($except)) {
  235. $this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW);
  236. $this->outputList($except);
  237. }
  238. }
  239. /**
  240. * Notifies user that fixtures were successfully unloaded.
  241. * @param array $fixtures
  242. */
  243. private function notifyUnloaded($fixtures)
  244. {
  245. $this->stdout("\nFixtures were successfully unloaded from namespace: ", Console::FG_YELLOW);
  246. $this->stdout(Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  247. $this->outputList($fixtures);
  248. }
  249. /**
  250. * Notifies user that fixtures were not found under fixtures path.
  251. * @param array $fixtures
  252. */
  253. private function notifyNotFound($fixtures)
  254. {
  255. $this->stdout("Some fixtures were not found under path:\n", Console::BG_RED);
  256. $this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN);
  257. $this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
  258. $this->outputList($fixtures);
  259. $this->stdout("\n");
  260. }
  261. /**
  262. * Prompts user with confirmation if fixtures should be loaded.
  263. * @param array $fixtures
  264. * @param array $except
  265. * @return boolean
  266. */
  267. private function confirmLoad($fixtures, $except)
  268. {
  269. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  270. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  271. if (count($this->globalFixtures)) {
  272. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  273. $this->outputList($this->globalFixtures);
  274. }
  275. if (count($fixtures)) {
  276. $this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW);
  277. $this->outputList($fixtures);
  278. }
  279. if (count($except)) {
  280. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  281. $this->outputList($except);
  282. }
  283. $this->stdout("\nBe aware that:\n", Console::BOLD);
  284. $this->stdout("Applying leads to purging of certain data in the database!\n", Console::FG_RED);
  285. return $this->confirm("\nLoad above fixtures?");
  286. }
  287. /**
  288. * Prompts user with confirmation for fixtures that should be unloaded.
  289. * @param array $fixtures
  290. * @param array $except
  291. * @return boolean
  292. */
  293. private function confirmUnload($fixtures, $except)
  294. {
  295. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  296. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  297. if (count($this->globalFixtures)) {
  298. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  299. $this->outputList($this->globalFixtures);
  300. }
  301. if (count($fixtures)) {
  302. $this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW);
  303. $this->outputList($fixtures);
  304. }
  305. if (count($except)) {
  306. $this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
  307. $this->outputList($except);
  308. }
  309. return $this->confirm("\nUnload fixtures?");
  310. }
  311. /**
  312. * Outputs data to the console as a list.
  313. * @param array $data
  314. */
  315. private function outputList($data)
  316. {
  317. foreach ($data as $index => $item) {
  318. $this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
  319. }
  320. }
  321. /**
  322. * Checks if needed to apply all fixtures.
  323. * @param string $fixture
  324. * @return boolean
  325. */
  326. public function needToApplyAll($fixture)
  327. {
  328. return $fixture === '*';
  329. }
  330. /**
  331. * Finds fixtures to be loaded, for example "User", if no fixtures were specified then all of them
  332. * will be searching by suffix "Fixture.php".
  333. * @param array $fixtures fixtures to be loaded
  334. * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists.
  335. */
  336. private function findFixtures(array $fixtures = [])
  337. {
  338. $fixturesPath = $this->getFixturePath();
  339. $filesToSearch = ['*Fixture.php'];
  340. $findAll = ($fixtures === []);
  341. if (!$findAll) {
  342. $filesToSearch = [];
  343. foreach ($fixtures as $fileName) {
  344. $filesToSearch[] = $fileName . 'Fixture.php';
  345. }
  346. }
  347. $files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]);
  348. $foundFixtures = [];
  349. foreach ($files as $fixture) {
  350. $foundFixtures[] = basename($fixture, 'Fixture.php');
  351. }
  352. return $foundFixtures;
  353. }
  354. /**
  355. * Returns valid fixtures config that can be used to load them.
  356. * @param array $fixtures fixtures to configure
  357. * @return array
  358. */
  359. private function getFixturesConfig($fixtures)
  360. {
  361. $config = [];
  362. foreach ($fixtures as $fixture) {
  363. $isNamespaced = (strpos($fixture, '\\') !== false);
  364. $fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
  365. if (class_exists($fullClassName)) {
  366. $config[] = $fullClassName;
  367. }
  368. }
  369. return $config;
  370. }
  371. /**
  372. * Filters fixtures by splitting them in two categories: one that should be applied and not.
  373. * If fixture is prefixed with "-", for example "-User", that means that fixture should not be loaded,
  374. * if it is not prefixed it is considered as one to be loaded. Returns array:
  375. *
  376. * ```php
  377. * [
  378. * 'apply' => [
  379. * 'User',
  380. * ...
  381. * ],
  382. * 'except' => [
  383. * 'Custom',
  384. * ...
  385. * ],
  386. * ]
  387. * ```
  388. * @param array $fixtures
  389. * @return array fixtures array with 'apply' and 'except' elements.
  390. */
  391. private function filterFixtures($fixtures)
  392. {
  393. $filtered = [
  394. 'apply' => [],
  395. 'except' => [],
  396. ];
  397. foreach ($fixtures as $fixture) {
  398. if (mb_strpos($fixture, '-') !== false) {
  399. $filtered['except'][] = str_replace('-', '', $fixture);
  400. } else {
  401. $filtered['apply'][] = $fixture;
  402. }
  403. }
  404. return $filtered;
  405. }
  406. /**
  407. * Returns fixture path that determined on fixtures namespace.
  408. * @return string fixture path
  409. */
  410. private function getFixturePath()
  411. {
  412. return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace));
  413. }
  414. }