Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions models/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
*
* @author Dmytro Naumenko <[email protected]>
*
* @property int $id
* @property string $name
* @property News[] $news
* @property int id
* @property string name
* @property News[] news
*/
class Tag extends ActiveRecord
{
Expand Down
48 changes: 36 additions & 12 deletions services/NewsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,41 @@
namespace app\services;

use app\models\News;
use app\models\NewsTags;
use app\models\Tag;

class NewsGenerator
{
protected $existingTags;

/**
* @param int $number Number of news to be generated
* @void
*/
public function generate($number)
{
$rows = [];
for ($i = 0; $i < $number; $i++) {
$this->createRandomNews();
$rows[] = $this->createRandomNews();
}
News::getDb()->createCommand()->batchInsert(News::tableName(), ['title', 'text'], $rows)->execute();

$rows = [];
foreach (News::find()->orderBy('id desc')->limit($number)->all() as $news) {
$rows = array_merge($rows, $this->generateTagsForNews($news));
}
NewsTags::getDb()->createCommand()->batchInsert(NewsTags::tableName(), ['news_id', 'tag_id'], $rows)->execute();
}

/**
* @return News
* @return array
*/
protected function createRandomNews()
{
$news = new News([
return [
'title' => $this->generateRandomTitle(),
'text' => $this->generateRandomText(),
]);
$news->save();
$this->generateTagsForNews($news);

return $news;
];
}

/**
Expand Down Expand Up @@ -64,27 +71,35 @@ protected function getRandomTag()
*/
protected function ensureTag($name)
{
if ($tag = Tag::find()->where(['name' => $name])->one()) {
return $tag;
if (isset($this->getExistingTags()[$name])) {
return $this->getExistingTags()[$name];
}

$tag = new Tag(['name' => $name]);
$tag->save();

$this->existingTags[$name] = $tag;

return $tag;
}

/**
* @param News $news
* @void
* @return array
*/
protected function generateTagsForNews($news)
{
$result = [];
$count = mt_rand(1, 5);

for ($i = 0; $i < $count; $i++) {
$news->link('tags', $this->getRandomTag());
$result[] = [
'news_id' => $news->id,
'tag_id' => $this->getRandomTag()->id
];
}

return $result;
}

protected function generateRandomTitle()
Expand All @@ -97,4 +112,13 @@ protected function generateRandomText()
return str_repeat('Lorem ipsum dolor sir emet.', mt_rand(7, 23));
}

private function getExistingTags()
{
if (!isset($this->existingTags)) {
$this->existingTags = Tag::find()->indexBy('name')->all();
}

return $this->existingTags;
}

}