FixtureController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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\faker;
  8. use Yii;
  9. use yii\console\Exception;
  10. use yii\helpers\Console;
  11. use yii\helpers\FileHelper;
  12. use yii\helpers\VarDumper;
  13. /**
  14. * This command creates fixtures based on a given template.
  15. *
  16. * Fixtures are one of the important paths in unit testing. To speed up developers
  17. * work these fixtures can be generated automatically, based on prepared template.
  18. * This command is a simple wrapper for the [Faker](https://github.com/fzaninotto/Faker) library.
  19. *
  20. * You should configure your application as follows (you can use any alias, not only "fixture"):
  21. *
  22. * ~~~
  23. * 'controllerMap' => [
  24. * 'fixture' => [
  25. * 'class' => 'yii\faker\FixtureController',
  26. * ],
  27. * ],
  28. * ~~~
  29. *
  30. * To start using the command you need to be familiar (read guide) with the Faker library and
  31. * generate fixtures template files, according to the given format:
  32. *
  33. * ```php
  34. * // users.php file under template path (by default @tests/unit/templates/fixtures)
  35. * return [
  36. * 'name' => $faker->firstName,
  37. * 'phone' => $faker->phoneNumber,
  38. * 'city' => $faker->city,
  39. * 'password' => Yii::$app->getSecurity()->generatePasswordHash('password_' . $index),
  40. * 'auth_key' => Yii::$app->getSecurity()->generateRandomString(),
  41. * 'intro' => $faker->sentence(7, true), // generate a sentence with 7 words
  42. * ];
  43. * ```
  44. *
  45. * If you use callback as an attribute value it will be called with the following three parameters:
  46. *
  47. * - `$faker`: the Faker generator instance
  48. * - `$index`: the current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.
  49. *
  50. * After you set all needed fields in callback, you need to return $fixture array back from the callback.
  51. *
  52. * After you prepared needed templates for tables you can simply generate your fixtures via command
  53. *
  54. * ~~~
  55. * yii fixture/generate user
  56. *
  57. * //generate fixtures from several templates, for example:
  58. * yii fixture/generate user profile team
  59. * ~~~
  60. *
  61. * In the code above "users" is template name, after this command run, new file named same as template
  62. * will be created under the `$fixtureDataPath` folder.
  63. * You can generate fixtures for all templates, for example:
  64. *
  65. * ~~~
  66. * yii fixture/generate-all
  67. * ~~~
  68. *
  69. * This command will generate fixtures for all template files that are stored under $templatePath and
  70. * store fixtures under `$fixtureDataPath` with file names same as templates names.
  71. *
  72. * You can specify how many fixtures per file you need by the second parameter. In the code below we generate
  73. * all fixtures and in each file there will be 3 rows (fixtures).
  74. *
  75. * ~~~
  76. * yii fixture/generate-all --count=3
  77. * ~~~
  78. *
  79. * You can specify different options of this command:
  80. *
  81. * ~~~
  82. * //generate fixtures in russian language
  83. * yii fixture/generate user --count=5 --language=ru_RU
  84. *
  85. * //read templates from the other path
  86. * yii fixture/generate-all --templatePath=@app/path/to/my/custom/templates
  87. *
  88. * //generate fixtures into other folders
  89. * yii fixture/generate-all --fixtureDataPath=@tests/unit/fixtures/subfolder1/subfolder2/subfolder3
  90. * ~~~
  91. *
  92. * You can see all available templates by running command:
  93. *
  94. * ~~~
  95. * //list all templates under default template path (i.e. '@tests/unit/templates/fixtures')
  96. * yii fixture/templates
  97. *
  98. * //list all templates under specified template path
  99. * yii fixture/templates --templatePath='@app/path/to/my/custom/templates'
  100. * ~~~
  101. *
  102. * You also can create your own data providers for custom tables fields, see Faker library guide for more info (https://github.com/fzaninotto/Faker);
  103. * After you created custom provider, for example:
  104. *
  105. * ~~~
  106. * class Book extends \Faker\Provider\Base
  107. * {
  108. *
  109. * public function title($nbWords = 5)
  110. * {
  111. * $sentence = $this->generator->sentence($nbWords);
  112. * return mb_substr($sentence, 0, mb_strlen($sentence) - 1);
  113. * }
  114. *
  115. * }
  116. * ~~~
  117. *
  118. * you can use it by adding it to the $providers property of the current command. In your console.php config:
  119. *
  120. * ~~~
  121. * 'controllerMap' => [
  122. * 'fixture' => [
  123. * 'class' => 'yii\faker\FixtureController',
  124. * 'providers' => [
  125. * 'app\tests\unit\faker\providers\Book',
  126. * ],
  127. * ],
  128. * ],
  129. * ~~~
  130. *
  131. * @property \Faker\Generator $generator This property is read-only.
  132. *
  133. * @author Mark Jebri <mark.github@yandex.ru>
  134. * @since 2.0.0
  135. */
  136. class FixtureController extends \yii\console\controllers\FixtureController
  137. {
  138. /**
  139. * @var string Alias to the template path, where all tables templates are stored.
  140. */
  141. public $templatePath = '@tests/unit/templates/fixtures';
  142. /**
  143. * @var string Alias to the fixture data path, where data files should be written.
  144. */
  145. public $fixtureDataPath = '@tests/unit/fixtures/data';
  146. /**
  147. * @var string Language to use when generating fixtures data.
  148. */
  149. public $language;
  150. /**
  151. * @var integer total count of data per fixture. Defaults to 2.
  152. */
  153. public $count = 2;
  154. /**
  155. * @var array Additional data providers that can be created by user and will be added to the Faker generator.
  156. * More info in [Faker](https://github.com/fzaninotto/Faker.) library docs.
  157. */
  158. public $providers = [];
  159. /**
  160. * @var \Faker\Generator Faker generator instance
  161. */
  162. private $_generator;
  163. /**
  164. * @inheritdoc
  165. */
  166. public function options($actionID)
  167. {
  168. return array_merge(parent::options($actionID), [
  169. 'templatePath', 'language', 'fixtureDataPath', 'count'
  170. ]);
  171. }
  172. /**
  173. * @inheritdoc
  174. */
  175. public function beforeAction($action)
  176. {
  177. if (parent::beforeAction($action)) {
  178. $this->checkPaths();
  179. $this->addProviders();
  180. return true;
  181. } else {
  182. return false;
  183. }
  184. }
  185. /**
  186. * Lists all available fixtures template files.
  187. */
  188. public function actionTemplates()
  189. {
  190. $foundTemplates = $this->findTemplatesFiles();
  191. if (!$foundTemplates) {
  192. $this->notifyNoTemplatesFound();
  193. } else {
  194. $this->notifyTemplatesCanBeGenerated($foundTemplates);
  195. }
  196. }
  197. /**
  198. * Generates fixtures and fill them with Faker data.
  199. * For example,
  200. *
  201. * ~~~
  202. * //generate fixtures in russian language
  203. * yii fixture/generate user --count=5 --language=ru_RU
  204. *
  205. * //generate several fixtures
  206. * yii fixture/generate user profile team
  207. * ~~~
  208. *
  209. * @throws \yii\base\InvalidParamException
  210. * @throws \yii\console\Exception
  211. */
  212. public function actionGenerate()
  213. {
  214. $templatesInput = func_get_args();
  215. if (empty($templatesInput)) {
  216. throw new Exception('You should specify input fixtures template files');
  217. }
  218. $foundTemplates = $this->findTemplatesFiles($templatesInput);
  219. $notFoundTemplates = array_diff($templatesInput, $foundTemplates);
  220. if ($notFoundTemplates) {
  221. $this->notifyNotFoundTemplates($notFoundTemplates);
  222. }
  223. if (!$foundTemplates) {
  224. $this->notifyNoTemplatesFound();
  225. return static::EXIT_CODE_NORMAL;
  226. }
  227. if (!$this->confirmGeneration($foundTemplates)) {
  228. return static::EXIT_CODE_NORMAL;
  229. }
  230. $templatePath = Yii::getAlias($this->templatePath);
  231. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  232. FileHelper::createDirectory($fixtureDataPath);
  233. $generatedTemplates = [];
  234. foreach ($foundTemplates as $templateName) {
  235. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  236. $generatedTemplates[] = $templateName;
  237. }
  238. $this->notifyTemplatesGenerated($generatedTemplates);
  239. }
  240. /**
  241. * Generates all fixtures template path that can be found.
  242. */
  243. public function actionGenerateAll()
  244. {
  245. $foundTemplates = $this->findTemplatesFiles();
  246. if (!$foundTemplates) {
  247. $this->notifyNoTemplatesFound();
  248. return static::EXIT_CODE_NORMAL;
  249. }
  250. if (!$this->confirmGeneration($foundTemplates)) {
  251. return static::EXIT_CODE_NORMAL;
  252. }
  253. $templatePath = Yii::getAlias($this->templatePath);
  254. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  255. FileHelper::createDirectory($fixtureDataPath);
  256. $generatedTemplates = [];
  257. foreach ($foundTemplates as $templateName) {
  258. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  259. $generatedTemplates[] = $templateName;
  260. }
  261. $this->notifyTemplatesGenerated($generatedTemplates);
  262. }
  263. /**
  264. * Notifies user that given fixtures template files were not found.
  265. * @param array $templatesNames
  266. * @since 2.0.4
  267. */
  268. protected function notifyNotFoundTemplates($templatesNames)
  269. {
  270. $this->stdout("The following fixtures templates were NOT found:\n\n", Console::FG_RED);
  271. foreach ($templatesNames as $name) {
  272. $this->stdout("\t * $name \n", Console::FG_GREEN);
  273. }
  274. $this->stdout("\n");
  275. }
  276. /**
  277. * Notifies user that there was not found any files matching given input conditions.
  278. * @since 2.0.4
  279. */
  280. protected function notifyNoTemplatesFound()
  281. {
  282. $this->stdout("No fixtures template files matching input conditions were found under the path:\n\n", Console::FG_RED);
  283. $this->stdout("\t " . Yii::getAlias($this->templatePath) . " \n\n", Console::FG_GREEN);
  284. }
  285. /**
  286. * Notifies user that given fixtures template files were generated.
  287. * @param array $templatesNames
  288. * @since 2.0.4
  289. */
  290. protected function notifyTemplatesGenerated($templatesNames)
  291. {
  292. $this->stdout("The following fixtures template files were generated:\n\n", Console::FG_YELLOW);
  293. foreach ($templatesNames as $name) {
  294. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  295. }
  296. $this->stdout("\n");
  297. }
  298. /**
  299. * Notifies user about templates which could be generated.
  300. * @param array $templatesNames
  301. * @since 2.0.4
  302. */
  303. protected function notifyTemplatesCanBeGenerated($templatesNames)
  304. {
  305. $this->stdout("Template files path: ", Console::FG_YELLOW);
  306. $this->stdout(Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  307. foreach ($templatesNames as $name) {
  308. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  309. }
  310. $this->stdout("\n");
  311. }
  312. /**
  313. * Returns array containing fixtures templates file names. You can specify what files to find
  314. * by the given parameter.
  315. * @param array $templatesNames template file names to search. If empty then all files will be searched.
  316. * @return array
  317. * @since 2.0.4
  318. */
  319. protected function findTemplatesFiles(array $templatesNames = [])
  320. {
  321. $findAll = ($templatesNames == []);
  322. if ($findAll) {
  323. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => ['*.php']]);
  324. } else {
  325. $filesToSearch = [];
  326. foreach ($templatesNames as $fileName) {
  327. $filesToSearch[] = $fileName . '.php';
  328. }
  329. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => $filesToSearch]);
  330. }
  331. $foundTemplates = [];
  332. foreach ($files as $fileName) {
  333. // strip templatePath from current template's full path
  334. $relativeName = str_replace(Yii::getAlias($this->templatePath) . DIRECTORY_SEPARATOR, "", $fileName);
  335. $relativeDir = dirname($relativeName) == '.' ? '' : dirname($relativeName) . '/';
  336. // strip extension
  337. $relativeName = $relativeDir . basename($relativeName,'.php');
  338. $foundTemplates[] = $relativeName;
  339. }
  340. return $foundTemplates;
  341. }
  342. /**
  343. * Returns Faker generator instance. Getter for private property.
  344. * @return \Faker\Generator
  345. */
  346. public function getGenerator()
  347. {
  348. if ($this->_generator === null) {
  349. $language = $this->language === null ? Yii::$app->language : $this->language;
  350. $this->_generator = \Faker\Factory::create(str_replace('-', '_', $language));
  351. }
  352. return $this->_generator;
  353. }
  354. /**
  355. * Check if the template path and migrations path exists and writable.
  356. */
  357. public function checkPaths()
  358. {
  359. $path = Yii::getAlias($this->templatePath, false);
  360. if (!$path || !is_dir($path)) {
  361. throw new Exception("The template path \"{$this->templatePath}\" does not exist");
  362. }
  363. }
  364. /**
  365. * Adds users providers to the faker generator.
  366. */
  367. public function addProviders()
  368. {
  369. foreach ($this->providers as $provider) {
  370. $this->generator->addProvider(new $provider($this->generator));
  371. }
  372. }
  373. /**
  374. * Returns exported to the string representation of given fixtures array.
  375. * @param array $fixtures
  376. * @return string exported fixtures format
  377. */
  378. public function exportFixtures($fixtures)
  379. {
  380. return "<?php\n\nreturn " . VarDumper::export($fixtures) . ";\n";
  381. }
  382. /**
  383. * Generates fixture from given template
  384. * @param string $_template_ the fixture template file
  385. * @param int $index the current fixture index
  386. * @return array fixture
  387. */
  388. public function generateFixture($_template_, $index)
  389. {
  390. // $faker and $index are exposed to the template file
  391. $faker = $this->getGenerator();
  392. return require($_template_);
  393. }
  394. /**
  395. * Generates fixture file by the given fixture template file.
  396. * @param string $templateName template file name
  397. * @param string $templatePath path where templates are stored
  398. * @param string $fixtureDataPath fixture data path where generated file should be written
  399. */
  400. public function generateFixtureFile($templateName, $templatePath, $fixtureDataPath)
  401. {
  402. $fixtures = [];
  403. for ($i = 0; $i < $this->count; $i++) {
  404. $fixtures[$templateName . $i] = $this->generateFixture($templatePath . '/' . $templateName . '.php', $i);
  405. }
  406. $content = $this->exportFixtures($fixtures);
  407. // data file full path
  408. $dataFile = $fixtureDataPath . '/'. $templateName . '.php';
  409. // data file directory, create if it doesn't exist
  410. $dataFileDir = dirname($dataFile);
  411. if (!file_exists($dataFileDir)) {
  412. FileHelper::createDirectory($dataFileDir);
  413. }
  414. file_put_contents($dataFile, $content);
  415. }
  416. /**
  417. * Prompts user with message if he confirm generation with given fixture templates files.
  418. * @param array $files
  419. * @return bool
  420. */
  421. public function confirmGeneration($files)
  422. {
  423. $this->stdout("Fixtures will be generated under the path: \n", Console::FG_YELLOW);
  424. $this->stdout("\t" . Yii::getAlias($this->fixtureDataPath) . "\n\n", Console::FG_GREEN);
  425. $this->stdout("Templates will be taken from path: \n", Console::FG_YELLOW);
  426. $this->stdout("\t" . Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  427. foreach ($files as $fileName) {
  428. $this->stdout("\t* " . $fileName . "\n", Console::FG_GREEN);
  429. }
  430. return $this->confirm('Generate above fixtures?');
  431. }
  432. }