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.

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