FixtureController.php 15 KB

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