FixtureController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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->printHelpMessage();
  105. return ExitCode::OK;
  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 ExitCode::OK;
  129. }
  130. if (!$this->confirmLoad($fixturesToLoad, $except)) {
  131. return ExitCode::OK;
  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 ExitCode::OK;
  142. }
  143. /**
  144. * Unloads the specified fixtures.
  145. *
  146. * For example,
  147. *
  148. * ```
  149. * # unload the fixture data specified by User and UserProfile.
  150. * yii fixture/unload "User, UserProfile"
  151. *
  152. * # unload all fixtures found under 'tests\unit\fixtures'
  153. * yii fixture/unload "*"
  154. *
  155. * # unload all fixtures except User and UserProfile
  156. * yii fixture/unload "*, -User, -UserProfile"
  157. * ```
  158. *
  159. * @param array $fixturesInput
  160. * @return int return code
  161. * @throws Exception if the specified fixture does not exist.
  162. */
  163. public function actionUnload(array $fixturesInput = [])
  164. {
  165. if ($fixturesInput === []) {
  166. $this->printHelpMessage();
  167. return ExitCode::OK;
  168. }
  169. $filtered = $this->filterFixtures($fixturesInput);
  170. $except = $filtered['except'];
  171. if (!$this->needToApplyAll($fixturesInput[0])) {
  172. $fixtures = $filtered['apply'];
  173. $foundFixtures = $this->findFixtures($fixtures);
  174. $notFoundFixtures = array_diff($fixtures, $foundFixtures);
  175. if ($notFoundFixtures) {
  176. $this->notifyNotFound($notFoundFixtures);
  177. }
  178. } else {
  179. $foundFixtures = $this->findFixtures();
  180. }
  181. $fixturesToUnload = array_diff($foundFixtures, $except);
  182. if (!$foundFixtures) {
  183. throw new Exception(
  184. 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
  185. "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
  186. );
  187. }
  188. if (!$fixturesToUnload) {
  189. $this->notifyNothingToUnload($foundFixtures, $except);
  190. return ExitCode::OK;
  191. }
  192. if (!$this->confirmUnload($fixturesToUnload, $except)) {
  193. return ExitCode::OK;
  194. }
  195. $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
  196. if (!$fixtures) {
  197. throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
  198. }
  199. $this->unloadFixtures($this->createFixtures($fixtures));
  200. $this->notifyUnloaded($fixtures);
  201. }
  202. /**
  203. * Show help message.
  204. * @param array $fixturesInput
  205. */
  206. private function printHelpMessage()
  207. {
  208. $this->stdout($this->getHelpSummary() . "\n");
  209. $helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
  210. $this->stdout("Use $helpCommand to get usage info.\n");
  211. }
  212. /**
  213. * Notifies user that fixtures were successfully loaded.
  214. * @param array $fixtures
  215. */
  216. private function notifyLoaded($fixtures)
  217. {
  218. $this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW);
  219. $this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  220. $this->outputList($fixtures);
  221. }
  222. /**
  223. * Notifies user that there are no fixtures to load according input conditions.
  224. * @param array $foundFixtures array of found fixtures
  225. * @param array $except array of names of fixtures that should not be loaded
  226. */
  227. public function notifyNothingToLoad($foundFixtures, $except)
  228. {
  229. $this->stdout("Fixtures to load could not be found according given conditions:\n\n", Console::FG_RED);
  230. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  231. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  232. if (count($foundFixtures)) {
  233. $this->stdout("\nFixtures founded under the namespace:\n\n", Console::FG_YELLOW);
  234. $this->outputList($foundFixtures);
  235. }
  236. if (count($except)) {
  237. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  238. $this->outputList($except);
  239. }
  240. }
  241. /**
  242. * Notifies user that there are no fixtures to unload according input conditions.
  243. * @param array $foundFixtures array of found fixtures
  244. * @param array $except array of names of fixtures that should not be loaded
  245. */
  246. public function notifyNothingToUnload($foundFixtures, $except)
  247. {
  248. $this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED);
  249. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  250. $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
  251. if (count($foundFixtures)) {
  252. $this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW);
  253. $this->outputList($foundFixtures);
  254. }
  255. if (count($except)) {
  256. $this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW);
  257. $this->outputList($except);
  258. }
  259. }
  260. /**
  261. * Notifies user that fixtures were successfully unloaded.
  262. * @param array $fixtures
  263. */
  264. private function notifyUnloaded($fixtures)
  265. {
  266. $this->stdout("\nFixtures were successfully unloaded from namespace: ", Console::FG_YELLOW);
  267. $this->stdout(Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
  268. $this->outputList($fixtures);
  269. }
  270. /**
  271. * Notifies user that fixtures were not found under fixtures path.
  272. * @param array $fixtures
  273. */
  274. private function notifyNotFound($fixtures)
  275. {
  276. $this->stdout("Some fixtures were not found under path:\n", Console::BG_RED);
  277. $this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN);
  278. $this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
  279. $this->outputList($fixtures);
  280. $this->stdout("\n");
  281. }
  282. /**
  283. * Prompts user with confirmation if fixtures should be loaded.
  284. * @param array $fixtures
  285. * @param array $except
  286. * @return bool
  287. */
  288. private function confirmLoad($fixtures, $except)
  289. {
  290. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  291. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  292. if (count($this->globalFixtures)) {
  293. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  294. $this->outputList($this->globalFixtures);
  295. }
  296. if (count($fixtures)) {
  297. $this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW);
  298. $this->outputList($fixtures);
  299. }
  300. if (count($except)) {
  301. $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
  302. $this->outputList($except);
  303. }
  304. $this->stdout("\nBe aware that:\n", Console::BOLD);
  305. $this->stdout("Applying leads to purging of certain data in the database!\n", Console::FG_RED);
  306. return $this->confirm("\nLoad above fixtures?");
  307. }
  308. /**
  309. * Prompts user with confirmation for fixtures that should be unloaded.
  310. * @param array $fixtures
  311. * @param array $except
  312. * @return bool
  313. */
  314. private function confirmUnload($fixtures, $except)
  315. {
  316. $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
  317. $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
  318. if (count($this->globalFixtures)) {
  319. $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
  320. $this->outputList($this->globalFixtures);
  321. }
  322. if (count($fixtures)) {
  323. $this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW);
  324. $this->outputList($fixtures);
  325. }
  326. if (count($except)) {
  327. $this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
  328. $this->outputList($except);
  329. }
  330. return $this->confirm("\nUnload fixtures?");
  331. }
  332. /**
  333. * Outputs data to the console as a list.
  334. * @param array $data
  335. */
  336. private function outputList($data)
  337. {
  338. foreach ($data as $index => $item) {
  339. $this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
  340. }
  341. }
  342. /**
  343. * Checks if needed to apply all fixtures.
  344. * @param string $fixture
  345. * @return bool
  346. */
  347. public function needToApplyAll($fixture)
  348. {
  349. return $fixture === '*';
  350. }
  351. /**
  352. * Finds fixtures to be loaded, for example "User", if no fixtures were specified then all of them
  353. * will be searching by suffix "Fixture.php".
  354. * @param array $fixtures fixtures to be loaded
  355. * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists.
  356. */
  357. private function findFixtures(array $fixtures = [])
  358. {
  359. $fixturesPath = $this->getFixturePath();
  360. $filesToSearch = ['*Fixture.php'];
  361. $findAll = ($fixtures === []);
  362. if (!$findAll) {
  363. $filesToSearch = [];
  364. foreach ($fixtures as $fileName) {
  365. $filesToSearch[] = $fileName . 'Fixture.php';
  366. }
  367. }
  368. $files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]);
  369. $foundFixtures = [];
  370. foreach ($files as $fixture) {
  371. $foundFixtures[] = $this->getFixtureRelativeName($fixture);
  372. }
  373. return $foundFixtures;
  374. }
  375. /**
  376. * Calculates fixture's name
  377. * Basically, strips [[getFixturePath()]] and `Fixture.php' suffix from fixture's full path.
  378. * @see getFixturePath()
  379. * @param string $fullFixturePath Full fixture path
  380. * @return string Relative fixture name
  381. */
  382. private function getFixtureRelativeName($fullFixturePath)
  383. {
  384. $fixturesPath = FileHelper::normalizePath($this->getFixturePath());
  385. $fullFixturePath = FileHelper::normalizePath($fullFixturePath);
  386. $relativeName = substr($fullFixturePath, strlen($fixturesPath) + 1);
  387. $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . DIRECTORY_SEPARATOR;
  388. return $relativeDir . basename($fullFixturePath, 'Fixture.php');
  389. }
  390. /**
  391. * Returns valid fixtures config that can be used to load them.
  392. * @param array $fixtures fixtures to configure
  393. * @return array
  394. */
  395. private function getFixturesConfig($fixtures)
  396. {
  397. $config = [];
  398. foreach ($fixtures as $fixture) {
  399. $isNamespaced = (strpos($fixture, '\\') !== false);
  400. // replace linux' path slashes to namespace backslashes, in case if $fixture is non-namespaced relative path
  401. $fixture = str_replace('/', '\\', $fixture);
  402. $fullClassName = $isNamespaced ? $fixture : $this->namespace . '\\' . $fixture;
  403. if (class_exists($fullClassName)) {
  404. $config[] = $fullClassName;
  405. } elseif (class_exists($fullClassName . 'Fixture')) {
  406. $config[] = $fullClassName . 'Fixture';
  407. }
  408. }
  409. return $config;
  410. }
  411. /**
  412. * Filters fixtures by splitting them in two categories: one that should be applied and not.
  413. *
  414. * If fixture is prefixed with "-", for example "-User", that means that fixture should not be loaded,
  415. * if it is not prefixed it is considered as one to be loaded. Returns array:
  416. *
  417. * ```php
  418. * [
  419. * 'apply' => [
  420. * 'User',
  421. * ...
  422. * ],
  423. * 'except' => [
  424. * 'Custom',
  425. * ...
  426. * ],
  427. * ]
  428. * ```
  429. * @param array $fixtures
  430. * @return array fixtures array with 'apply' and 'except' elements.
  431. */
  432. private function filterFixtures($fixtures)
  433. {
  434. $filtered = [
  435. 'apply' => [],
  436. 'except' => [],
  437. ];
  438. foreach ($fixtures as $fixture) {
  439. if (mb_strpos($fixture, '-') !== false) {
  440. $filtered['except'][] = str_replace('-', '', $fixture);
  441. } else {
  442. $filtered['apply'][] = $fixture;
  443. }
  444. }
  445. return $filtered;
  446. }
  447. /**
  448. * Returns fixture path that determined on fixtures namespace.
  449. * @throws InvalidConfigException if fixture namespace is invalid
  450. * @return string fixture path
  451. */
  452. private function getFixturePath()
  453. {
  454. try {
  455. return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace));
  456. } catch (InvalidParamException $e) {
  457. throw new InvalidConfigException('Invalid fixture namespace: "' . $this->namespace . '". Please, check your FixtureController::namespace parameter');
  458. }
  459. }
  460. }