Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

469 rindas
14KB

  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. public function beforeAction($action)
  173. {
  174. if (parent::beforeAction($action)) {
  175. $this->checkPaths();
  176. $this->addProviders();
  177. return true;
  178. } else {
  179. return false;
  180. }
  181. }
  182. /**
  183. * Lists all available fixtures template files.
  184. */
  185. public function actionTemplates()
  186. {
  187. $foundTemplates = $this->findTemplatesFiles();
  188. if (!$foundTemplates) {
  189. $this->notifyNoTemplatesFound();
  190. } else {
  191. $this->notifyTemplatesCanBeGenerated($foundTemplates);
  192. }
  193. }
  194. /**
  195. * Generates fixtures and fill them with Faker data.
  196. * For example,
  197. *
  198. * ~~~
  199. * //generate fixtures in russian language
  200. * yii fixture/generate user --count=5 --language=ru_RU
  201. *
  202. * //generate several fixtures
  203. * yii fixture/generate user profile team
  204. * ~~~
  205. *
  206. * @throws \yii\base\InvalidParamException
  207. * @throws \yii\console\Exception
  208. */
  209. public function actionGenerate()
  210. {
  211. $templatesInput = func_get_args();
  212. if (empty($templatesInput)) {
  213. throw new Exception('You should specify input fixtures template files');
  214. }
  215. $foundTemplates = $this->findTemplatesFiles($templatesInput);
  216. $notFoundTemplates = array_diff($templatesInput, $foundTemplates);
  217. if ($notFoundTemplates) {
  218. $this->notifyNotFoundTemplates($notFoundTemplates);
  219. }
  220. if (!$foundTemplates) {
  221. $this->notifyNoTemplatesFound();
  222. return static::EXIT_CODE_NORMAL;
  223. }
  224. if (!$this->confirmGeneration($foundTemplates)) {
  225. return static::EXIT_CODE_NORMAL;
  226. }
  227. $templatePath = Yii::getAlias($this->templatePath);
  228. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  229. FileHelper::createDirectory($fixtureDataPath);
  230. $generatedTemplates = [];
  231. foreach ($foundTemplates as $templateName) {
  232. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  233. $generatedTemplates[] = $templateName;
  234. }
  235. $this->notifyTemplatesGenerated($generatedTemplates);
  236. }
  237. /**
  238. * Generates all fixtures template path that can be found.
  239. */
  240. public function actionGenerateAll()
  241. {
  242. $foundTemplates = $this->findTemplatesFiles();
  243. if (!$foundTemplates) {
  244. $this->notifyNoTemplatesFound();
  245. return static::EXIT_CODE_NORMAL;
  246. }
  247. if (!$this->confirmGeneration($foundTemplates)) {
  248. return static::EXIT_CODE_NORMAL;
  249. }
  250. $templatePath = Yii::getAlias($this->templatePath);
  251. $fixtureDataPath = Yii::getAlias($this->fixtureDataPath);
  252. FileHelper::createDirectory($fixtureDataPath);
  253. $generatedTemplates = [];
  254. foreach ($foundTemplates as $templateName) {
  255. $this->generateFixtureFile($templateName, $templatePath, $fixtureDataPath);
  256. $generatedTemplates[] = $templateName;
  257. }
  258. $this->notifyTemplatesGenerated($generatedTemplates);
  259. }
  260. /**
  261. * Notifies user that given fixtures template files were not found.
  262. * @param array $templatesNames
  263. */
  264. private function notifyNotFoundTemplates($templatesNames)
  265. {
  266. $this->stdout("The following fixtures templates were NOT found:\n\n", Console::FG_RED);
  267. foreach ($templatesNames as $name) {
  268. $this->stdout("\t * $name \n", Console::FG_GREEN);
  269. }
  270. $this->stdout("\n");
  271. }
  272. /**
  273. * Notifies user that there was not found any files matching given input conditions.
  274. */
  275. private function notifyNoTemplatesFound()
  276. {
  277. $this->stdout("No fixtures template files matching input conditions were found under the path:\n\n", Console::FG_RED);
  278. $this->stdout("\t " . Yii::getAlias($this->templatePath) . " \n\n", Console::FG_GREEN);
  279. }
  280. /**
  281. * Notifies user that given fixtures template files were generated.
  282. * @param array $templatesNames
  283. */
  284. private function notifyTemplatesGenerated($templatesNames)
  285. {
  286. $this->stdout("The following fixtures template files were generated:\n\n", Console::FG_YELLOW);
  287. foreach ($templatesNames as $name) {
  288. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  289. }
  290. $this->stdout("\n");
  291. }
  292. private function notifyTemplatesCanBeGenerated($templatesNames)
  293. {
  294. $this->stdout("Template files path: ", Console::FG_YELLOW);
  295. $this->stdout(Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  296. foreach ($templatesNames as $name) {
  297. $this->stdout("\t* " . $name . "\n", Console::FG_GREEN);
  298. }
  299. $this->stdout("\n");
  300. }
  301. /**
  302. * Returns array containing fixtures templates file names. You can specify what files to find
  303. * by the given parameter.
  304. * @param array $templatesNames template file names to search. If empty then all files will be searched.
  305. * @return array
  306. */
  307. private function findTemplatesFiles(array $templatesNames = [])
  308. {
  309. $findAll = ($templatesNames == []);
  310. if ($findAll) {
  311. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => ['*.php']]);
  312. } else {
  313. $filesToSearch = [];
  314. foreach ($templatesNames as $fileName) {
  315. $filesToSearch[] = $fileName . '.php';
  316. }
  317. $files = FileHelper::findFiles(Yii::getAlias($this->templatePath), ['only' => $filesToSearch]);
  318. }
  319. $foundTemplates = [];
  320. foreach ($files as $fileName) {
  321. $foundTemplates[] = basename($fileName, '.php');
  322. }
  323. return $foundTemplates;
  324. }
  325. /**
  326. * Returns Faker generator instance. Getter for private property.
  327. * @return \Faker\Generator
  328. */
  329. public function getGenerator()
  330. {
  331. if ($this->_generator === null) {
  332. $language = $this->language === null ? Yii::$app->language : $this->language;
  333. $this->_generator = \Faker\Factory::create(str_replace('-', '_', $language));
  334. }
  335. return $this->_generator;
  336. }
  337. /**
  338. * Check if the template path and migrations path exists and writable.
  339. */
  340. public function checkPaths()
  341. {
  342. $path = Yii::getAlias($this->templatePath, false);
  343. if (!$path || !is_dir($path)) {
  344. throw new Exception("The template path \"{$this->templatePath}\" does not exist");
  345. }
  346. }
  347. /**
  348. * Adds users providers to the faker generator.
  349. */
  350. public function addProviders()
  351. {
  352. foreach ($this->providers as $provider) {
  353. $this->generator->addProvider(new $provider($this->generator));
  354. }
  355. }
  356. /**
  357. * Returns exported to the string representation of given fixtures array.
  358. * @param array $fixtures
  359. * @return string exported fixtures format
  360. */
  361. public function exportFixtures($fixtures)
  362. {
  363. return "<?php\n\nreturn " . VarDumper::export($fixtures) . ";\n";
  364. }
  365. /**
  366. * Generates fixture from given template
  367. * @param string $_template_ the fixture template file
  368. * @param integer $index the current fixture index
  369. * @return array fixture
  370. */
  371. public function generateFixture($_template_, $index)
  372. {
  373. // $faker and $index are exposed to the template file
  374. $faker = $this->getGenerator();
  375. return require($_template_);
  376. }
  377. /**
  378. * Generates fixture file by the given fixture template file.
  379. * @param string $templateName template file name
  380. * @param string $templatePath path where templates are stored
  381. * @param string $fixtureDataPath fixture data path where generated file should be written
  382. */
  383. public function generateFixtureFile($templateName, $templatePath, $fixtureDataPath)
  384. {
  385. $fixtures = [];
  386. for ($i = 0; $i < $this->count; $i++) {
  387. $fixtures[$i] = $this->generateFixture($templatePath . '/' . $templateName . '.php', $i);
  388. }
  389. $content = $this->exportFixtures($fixtures);
  390. file_put_contents($fixtureDataPath . '/'. $templateName . '.php', $content);
  391. }
  392. /**
  393. * Prompts user with message if he confirm generation with given fixture templates files.
  394. * @param array $files
  395. * @return boolean
  396. */
  397. public function confirmGeneration($files)
  398. {
  399. $this->stdout("Fixtures will be generated under the path: \n", Console::FG_YELLOW);
  400. $this->stdout("\t" . Yii::getAlias($this->fixtureDataPath) . "\n\n", Console::FG_GREEN);
  401. $this->stdout("Templates will be taken from path: \n", Console::FG_YELLOW);
  402. $this->stdout("\t" . Yii::getAlias($this->templatePath) . "\n\n", Console::FG_GREEN);
  403. foreach ($files as $fileName) {
  404. $this->stdout("\t* " . $fileName . "\n", Console::FG_GREEN);
  405. }
  406. return $this->confirm('Generate above fixtures?');
  407. }
  408. }