FixtureController.php 16 KB

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