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\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. * ```php
  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. * ```php
  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. * return [
  122. * 'controllerMap' => [
  123. * 'fixture' => [
  124. * 'class' => 'yii\faker\FixtureController',
  125. * 'providers' => [
  126. * 'app\tests\unit\faker\providers\Book',
  127. * ],
  128. * ],
  129. * // ...
  130. * ],
  131. * // ...
  132. * ];
  133. * ```
  134. *
  135. * @property \Faker\Generator $generator This property is read-only.
  136. *
  137. * @author Mark Jebri <mark.github@yandex.ru>
  138. * @since 2.0.0
  139. */
  140. class FixtureController extends \yii\console\controllers\FixtureController
  141. {
  142. /**
  143. * @var string Alias to the template path, where all tables templates are stored.
  144. */
  145. public $templatePath = '@tests/unit/templates/fixtures';
  146. /**
  147. * @var string Alias to the fixture data path, where data files should be written.
  148. */
  149. public $fixtureDataPath = '@tests/unit/fixtures/data';
  150. /**
  151. * @var string Language to use when generating fixtures data.
  152. */
  153. public $language;
  154. /**
  155. * @var integer total count of data per fixture. Defaults to 2.
  156. */
  157. public $count = 2;
  158. /**
  159. * @var array Additional data providers that can be created by user and will be added to the Faker generator.
  160. * More info in [Faker](https://github.com/fzaninotto/Faker.) library docs.
  161. */
  162. public $providers = [];
  163. /**
  164. * @var \Faker\Generator Faker generator instance
  165. */
  166. private $_generator;
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function options($actionID)
  171. {
  172. return array_merge(parent::options($actionID), [
  173. 'templatePath', 'language', 'fixtureDataPath', 'count'
  174. ]);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function beforeAction($action)
  180. {
  181. if (parent::beforeAction($action)) {
  182. $this->checkPaths();
  183. $this->addProviders();
  184. return true;
  185. }
  186. return false;
  187. }
  188. /**
  189. * Lists all available fixtures template files.
  190. */
  191. public function actionTemplates()
  192. {
  193. $foundTemplates = $this->findTemplatesFiles();
  194. if (!$foundTemplates) {
  195. $this->notifyNoTemplatesFound();
  196. } else {
  197. $this->notifyTemplatesCanBeGenerated($foundTemplates);
  198. }
  199. }
  200. /**
  201. * Generates fixtures and fill them with Faker data.
  202. * For example,
  203. *
  204. * ```
  205. * //generate fixtures in russian language
  206. * yii fixture/generate user --count=5 --language=ru_RU
  207. *
  208. * //generate several fixtures
  209. * yii fixture/generate user profile team
  210. * ```
  211. *
  212. * @throws \yii\base\InvalidParamException
  213. * @throws \yii\console\Exception
  214. */
  215. public function actionGenerate()
  216. {
  217. $templatesInput = func_get_args();
  218. if (empty($templatesInput)) {
  219. throw new Exception('You should specify input fixtures template files');
  220. }
  221. $foundTemplates = $this->findTemplatesFiles($templatesInput);
  222. $notFoundTemplates = array_diff($templatesInput, $foundTemplates);
  223. if ($notFoundTemplates) {
  224. $this->notifyNotFoundTemplates($notFoundTemplates);
  225. }
  226. if (!$foundTemplates) {
  227. $this->notifyNoTemplatesFound();
  228. return static::EXIT_CODE_NORMAL;
  229. }
  230. if (!$this->confirmGeneration($foundTemplates)) {
  231. return static::EXIT_CODE_NORMAL;
  232. }
  233. $templatePath = Yii::getAlias($this->templatePath);
  234. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  235. FileHelper::createDirectory($fixtureDataPath);
  236. $generatedTemplates = [];
  237. foreach ($foundTemplates as $templateName) {
  238. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  239. $generatedTemplates[] = $templateName;
  240. }
  241. $this->notifyTemplatesGenerated($generatedTemplates);
  242. }
  243. /**
  244. * Generates all fixtures template path that can be found.
  245. */
  246. public function actionGenerateAll()
  247. {
  248. $foundTemplates = $this->findTemplatesFiles();
  249. if (!$foundTemplates) {
  250. $this->notifyNoTemplatesFound();
  251. return static::EXIT_CODE_NORMAL;
  252. }
  253. if (!$this->confirmGeneration($foundTemplates)) {
  254. return static::EXIT_CODE_NORMAL;
  255. }
  256. $templatePath = Yii::getAlias($this->templatePath);
  257. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  258. FileHelper::createDirectory($fixtureDataPath);
  259. $generatedTemplates = [];
  260. foreach ($foundTemplates as $templateName) {
  261. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  262. $generatedTemplates[] = $templateName;
  263. }
  264. $this->notifyTemplatesGenerated($generatedTemplates);
  265. }
  266. /**
  267. * Notifies user that given fixtures template files were not found.
  268. * @param array $templatesNames
  269. * @since 2.0.4
  270. */
  271. protected function notifyNotFoundTemplates($templatesNames)
  272. {
  273. $this->stdout("The following fixtures templates were NOT found:\n\n", Console::FG_RED);
  274. foreach ($templatesNames as $name) {
  275. $this->stdout("\t * $name \n", Console::FG_GREEN);
  276. }
  277. $this->stdout("\n");
  278. }
  279. /**
  280. * Notifies user that there was not found any files matching given input conditions.
  281. * @since 2.0.4
  282. */
  283. protected function notifyNoTemplatesFound()
  284. {
  285. $this->stdout("No fixtures template files matching input conditions were found under the path:\n\n", Console::FG_RED);
  286. $this->stdout("\t " . Yii::getAlias($this->templatePath) . " \n\n", Console::FG_GREEN);
  287. }
  288. /**
  289. * Notifies user that given fixtures template files were generated.
  290. * @param array $templatesNames
  291. * @since 2.0.4
  292. */
  293. protected function notifyTemplatesGenerated($templatesNames)
  294. {
  295. $this->stdout("The following fixtures template files were generated:\n\n", Console::FG_YELLOW);
  296. foreach ($templatesNames as $name) {
  297. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  298. }
  299. $this->stdout("\n");
  300. }
  301. /**
  302. * Notifies user about templates which could be generated.
  303. * @param array $templatesNames
  304. * @since 2.0.4
  305. */
  306. protected function notifyTemplatesCanBeGenerated($templatesNames)
  307. {
  308. $this->stdout("Template files path: ", Console::FG_YELLOW);
  309. $this->stdout(Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  310. foreach ($templatesNames as $name) {
  311. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  312. }
  313. $this->stdout("\n");
  314. }
  315. /**
  316. * Returns array containing fixtures templates file names. You can specify what files to find
  317. * by the given parameter.
  318. * @param array $templatesNames template file names to search. If empty then all files will be searched.
  319. * @return array
  320. * @since 2.0.4
  321. */
  322. protected function findTemplatesFiles(array $templatesNames = [])
  323. {
  324. $findAll = ($templatesNames == []);
  325. if ($findAll) {
  326. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => ['*.php']]);
  327. } else {
  328. $filesToSearch = [];
  329. foreach ($templatesNames as $fileName) {
  330. $filesToSearch[] = $fileName . '.php';
  331. }
  332. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => $filesToSearch]);
  333. }
  334. $foundTemplates = [];
  335. foreach ($files as $fileName) {
  336. // strip templatePath from current template's full path
  337. $relativeName = str_replace(Yii::getAlias($this->templatePath) . DIRECTORY_SEPARATOR, "", $fileName);
  338. $relativeDir = dirname($relativeName) == '.' ? '' : dirname($relativeName) . '/';
  339. // strip extension
  340. $relativeName = $relativeDir . basename($relativeName,'.php');
  341. $foundTemplates[] = $relativeName;
  342. }
  343. return $foundTemplates;
  344. }
  345. /**
  346. * Returns Faker generator instance. Getter for private property.
  347. * @return \Faker\Generator
  348. */
  349. public function getGenerator()
  350. {
  351. if ($this->_generator === null) {
  352. $language = $this->language === null ? Yii::$app->language : $this->language;
  353. $this->_generator = \Faker\Factory::create(str_replace('-', '_', $language));
  354. }
  355. return $this->_generator;
  356. }
  357. /**
  358. * Check if the template path and migrations path exists and writable.
  359. */
  360. public function checkPaths()
  361. {
  362. $path = Yii::getAlias($this->templatePath, false);
  363. if (!$path || !is_dir($path)) {
  364. throw new Exception("The template path \"{$this->templatePath}\" does not exist");
  365. }
  366. }
  367. /**
  368. * Adds users providers to the faker generator.
  369. */
  370. public function addProviders()
  371. {
  372. foreach ($this->providers as $provider) {
  373. $this->generator->addProvider(new $provider($this->generator));
  374. }
  375. }
  376. /**
  377. * Returns exported to the string representation of given fixtures array.
  378. * @param array $fixtures
  379. * @return string exported fixtures format
  380. */
  381. public function exportFixtures($fixtures)
  382. {
  383. return "<?php\n\nreturn " . VarDumper::export($fixtures) . ";\n";
  384. }
  385. /**
  386. * Generates fixture from given template
  387. * @param string $_template_ the fixture template file
  388. * @param int $index the current fixture index
  389. * @return array fixture
  390. */
  391. public function generateFixture($_template_, $index)
  392. {
  393. // $faker and $index are exposed to the template file
  394. $faker = $this->getGenerator();
  395. return require($_template_);
  396. }
  397. /**
  398. * Generates fixture file by the given fixture template file.
  399. * @param string $templateName template file name
  400. * @param string $templatePath path where templates are stored
  401. * @param string $fixtureDataPath fixture data path where generated file should be written
  402. */
  403. public function generateFixtureFile($templateName, $templatePath, $fixtureDataPath)
  404. {
  405. $fixtures = [];
  406. for ($i = 0; $i < $this->count; $i++) {
  407. $fixtures[$templateName . $i] = $this->generateFixture($templatePath . '/' . $templateName . '.php', $i);
  408. }
  409. $content = $this->exportFixtures($fixtures);
  410. // data file full path
  411. $dataFile = $fixtureDataPath . '/'. $templateName . '.php';
  412. // data file directory, create if it doesn't exist
  413. $dataFileDir = dirname($dataFile);
  414. if (!file_exists($dataFileDir)) {
  415. FileHelper::createDirectory($dataFileDir);
  416. }
  417. file_put_contents($dataFile, $content);
  418. }
  419. /**
  420. * Prompts user with message if he confirm generation with given fixture templates files.
  421. * @param array $files
  422. * @return bool
  423. */
  424. public function confirmGeneration($files)
  425. {
  426. $this->stdout("Fixtures will be generated under the path: \n", Console::FG_YELLOW);
  427. $this->stdout("\t" . Yii::getAlias($this->fixtureDataPath) . "\n\n", Console::FG_GREEN);
  428. $this->stdout("Templates will be taken from path: \n", Console::FG_YELLOW);
  429. $this->stdout("\t" . Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  430. foreach ($files as $fileName) {
  431. $this->stdout("\t* " . $fileName . "\n", Console::FG_GREEN);
  432. }
  433. return $this->confirm('Generate above fixtures?');
  434. }
  435. }